Xml XPath queries are not so straight forward and each time I'm using them I struggle it.
On one of our inside tools I needed to parse an Xml file but the selected nodes were reflected from their value and not from their name only. I was used to have a SelectSingleNode(nodeName) or SelectNodes(nodeName) that did the job for me but now I needed something else.
Here's an example of the Xml:
<Data>
<Table>
<Row>
<Field Name="Name" Value="object1"/>
<Field Name="Type" Value="int"/>
<Field Name="Value" Value="1"/>
</Row>
<Row>
<Field Name="Name" Value="object2"/>
<Field Name="Type" Value="int"/>
<Field Name="Value" Value="2"/>
</Row>
<Row>
<Field Name="Name" Value="object3"/>
<Field Name="Type" Value="string"/>
<Field Name="Value" Value="aaa"/>
</Row>
<Row>
<Field Name="Name" Value="object4"/>
<Field Name="Type" Value="string"/>
<Field Name="Value" Value="bbb"/>
</Row>
<Row>
<Field Name="Name" Value="object5"/>
<Field Name="Type" Value="int"/>
<Field Name="Value" Value="3"/>
</Row>
</Table>
</Data>
Now, I would like to select all <Field> nodes that are from type int. So I need to write query that will find all <Field> nodes that have "Name" attribute with the value "Type" and "Value" attribute with the value "int".
Here's how the query should look when you are using XmlDocument.SelectNodes or XmlDocument.SelectSingleNode:
"//Field[@Name='Type'][@Value='int']"
Now, how do I select all the <Row> nodes that correspond to this query? I've tried and found out that a nested query actually works...
"//Row[Field[@Name='Type'][@Value='int']]"
Xml XPath queried can be very powerful.
No comments:
Post a Comment