Search code examples
vb.netxpathxmldocument

How to select the tag based on tag name and get its count


Not able to select the node with the tag name.

Smaple XML:

<author-group id="a001">
<author id="aa001">
  <given-name id="g001">Name</given-name>
  <surname id="s001">Name</surname>
</author>
<author id="aa002">
 <given-name id="g002">Name</given-name>
 <surname id="s002">Name</surname>
</author>
<author id="aa003">
   <given-name id="g003">Name</given-name>
   <surname id="s003">Name</surname>
</author>
</author-group>

Code tried:

Dim xDom As New Xml.XmlDocument
xDom .LoadXml(XMLStr)
Dim Lst As XmlNodeList = xDom.SelectNodes("//author")
Dim NodeCount as Integer =Lst.Count()

The count is coming as zero..


Solution

  • The xmlns attribute defines so called default namespace that applies to all content under the element on which the element occurs. However, your XPath does not specify any namespaces which means that it will only find author elements that are not in any namespace. You are therefore effectively looking for a wrong element name.

    XPath queries that use namespaces require a XmlNamespaceManager that provides a mapping of namespace prefixes to namespaces. It is also possible to use default namespaces in the XPath in the same way as follows.

    Substitute the default namespace URI for xxx in the following snippet, and execute this after loading xDom with your document:

    'Create an XmlNamespaceManager for resolving namespaces.
    Dim nsmgr as XmlNamespaceManager = new XmlNamespaceManager(xDom.NameTable)
    nsmgr.AddNamespace(String.Empty, "xxx")
    
    Dim nodeList as XmlNodeList 
    Dim root as XmlElement = xDom.DocumentElement
    nodeList = root.SelectNodes("//author", nsmgr)