How to select two attributes from the same node with one expression in XPath?

XpathAttributes

Xpath Problem Overview


For example:

//person[@id='abc123']/@haircolor|/@weight"

PS. there are lots of "person" records

Xpath Solutions


Solution 1 - Xpath

Try this:

//person[@id='abc123']/@*[name()='weight' or name()='haircolor']

If you're using an XPath 2.0 processor, you may also use a prettier option:

//person[@id='abc123']/(@haircolor|@weight)`

Solution 2 - Xpath

Are you wanting to search for person nodes based on the value of multiple attributes. If that's the question then you can just use ands e.g.

//person[@id='abc123' and @haircolor='blue' and @weight='...']

If you want to search on a single attribute, but return the values of the other attributes, I would do something like this:

 <xsl:template match="person[@id='abc123']">
     <xsl:value-of select="@haircolor"/>
     <xsl:value-of select="@weight"/>
  </xsl:template>

Solution 3 - Xpath

If you are trying to get the values of the specified attributes I would suggest introducing a variable for the requested person.

<xsl:variable name="person" select="//person[@id = 'abc123']" />

After that you can get any attribute from the requested person by using the specified variable.

<xsl:value-of select="$person/@haircolor" />
<xsl:value-of select="$person/@weight" />

Solution 4 - Xpath

Sample XML:

<X>
<Y ATTRIB1=attrib1_value ATTRIB2=attrib2_value/>
</X>

string xPath="/" + X + "/" + Y +
"[@" + ATTRIB1 + "='" + attrib1_value + "']" +
"[@" + ATTRIB2 + "='" + attrib2_value + "']"

XPath Testbed: http://www.whitebeam.org/library/guide/TechNotes/xpathtestbed.rhtm

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjacobView Question on Stackoverflow
Solution 1 - XpathKobiView Answer on Stackoverflow
Solution 2 - XpathplanetjonesView Answer on Stackoverflow
Solution 3 - XpathOsiris76View Answer on Stackoverflow
Solution 4 - XpathManjeshView Answer on Stackoverflow