vb.net xml xpath wildcards

  • Thread starter Thread starter marfi95
  • Start date Start date
M

marfi95

I'm just starting to learn xpath, so if I have the following xml

<Root>
<Data 1>
<Child 1></Child 1>
<Child 2></Child 2>
</Data 1>
<Data 2>
<Child 1></Child 1>
<Child 2></Child 2>
</Data 2>
</Root>

Is there an xpath expression with SelectNodes that I can use to get
the number of nodes that start with <Data>

I thought I could use "Root/Data*", but that didn't seem to work.

Thanks !
Mark
 
Dim count As Integer = 0

Dim nodelist = As XmlNodeList = xmldocument.SelectNodes("//*")

For Each node As XmlNode In nodelist
If node.Name.StartsWith("Data") Then count += 1
Next

Console.WriteLine(count)
 
However if you Xml was constructed thus:

<Root>
<Data id="1">
<Child id="1" />
<Child id="2" />
</Data>
<Data id="2">
<Child id="1" />
<Child id="2" />
</Data>
</Root>

then you could simply use:

Console.WriteLine(xmldocument.SelectNodes("//Data").Count)
 
However if you Xml was constructed thus:

<Root>
<Data id="1">
<Child id="1" />
<Child id="2" />
</Data>
<Data id="2">
<Child id="1" />
<Child id="2" />
</Data>
</Root>

then you could simply use:

Console.WriteLine(xmldocument.SelectNodes("//Data").Count)








- Show quoted text -

Thanks ! I'll try that. I have some control over the XML itself, so
I might go the way you suggested in the 2nd approach.
 
Back
Top