Reputation: 211
I was under the impression that a node can be anything at all, be it element, attribute, etc etc.
I was looking at trying to iterate through a node list, eg ....
Dim xmlDoc As New Xml.XmlDocument
xmlDoc.LoadXml("
< main1 test1 = 'any' test2 = 'any2' >
< test1 > ttr < /test1 >
< test1 > ttr < /test1 >
< test1 > ttr < /test1 >
< test1 > ttr < /test1 >
< /main1 >")
Question 1
Why does the following return only the elements, and not the attributes:
For Each objnode As Xml.XmlNode In xmlDoc.DocumentElement.ChildNodes
Console.WriteLine(objnode.Name)
Next
Question 2
How can I iterate through all nodes, regardless of type, using xpath?
Upvotes: 0
Views: 1470
Reputation: 167516
Well in the DOM model that System.Xml.XmlDocument/XmlElement/XmlNode implement the ChildNodes collection gives you all nodes considered child nodes of the container node, that can be element nodes, text nodes, comment nodes, processing instruction nodes (and for the XmlDocument a DOCTYPE node and the XML declaration). Attribute nodes are not considered child nodes in that model so you won't find them in the ChildNodes collection. You can access the Attributes collection if you are interested.
[edit]
Well you can use the XPath union operator |
to select and process the union of nodes so with the XML being
<!-- comment 1 -->
<root att1="value 2" att2="value 2">Text<!-- comment 2 --><child att3="value 3">
<descendant/>
</child>
</root>
the following snippet of VB
Dim doc As New XmlDocument()
doc.Load("file.xml")
For Each node As XmlNode In doc.SelectNodes("//node() | //@*")
Console.WriteLine("Found node of type {0} with name {1}", node.NodeType, node.Name)
Next
outputs
Found node of type Comment with name #comment
Found node of type Element with name root
Found node of type Attribute with name att1
Found node of type Attribute with name att2
Found node of type Text with name #text
Found node of type Comment with name #comment
Found node of type Element with name child
Found node of type Attribute with name att3
Found node of type Element with name descendant
So that way you have one path expression selecting both attributes as well as element nodes, text nodes and comment nodes.
You should also be aware that DOM and XSLT/XPath have some mismatch in their tree models, for instance DOM distinguishes normal text nodes and CDATA section nodes, XPath does not do that. And the DOM allows adjacent text nodes, XPath does not do that. So while you can often write XPath queries against DOM trees and Microsoft supports that with both MSXML's DOM implementation and .NET's DOM implementation you need to be aware of subtle differences between the tree models XPath is defined against and you use XPath with when doing SelectSingleNode or SelectNodes in System.Xml.XmlDocument/XmlElement/XmlNode.
Upvotes: 3