I have been using .SelectNodes()
for some time, to get the child nodes of a particular node, and it works but as files get bigger it seems to get slower. So I started using .ChildNodes
and I am finding that it gets more than just the child nodes, it goes deeper getting grand child nodes.
Given this
$xml = [Xml]@"
<root>
<one>
<element1>element text</element1>
<element2>element text</element2>
<two>
<element3>element text</element3>
</two>
<name>Name text</name>
</one>
</root>
"@
foreach ($element in $xml.DocumentElement.ChildNodes | where {$_.NodeType -eq 'Element'}) {
Write-Host "$($element.Name) $($element.InnerText)"
}
I would have expected to only get back the single <one>
node, as it is the only child node of root. And yet what I get back is Name text element textelement textelement textName text
which makes no sense at all to me. Especially since I would at least have expected multiple items with the last line being name Name text
. Instead the first item in the line is the last node's name.
Now I know naming a node 'name' is a bad idea, and I am working on code to address that. But even if I change the name of that node, so <nametext>Name text</nametext>
, what I get back is a different kind of wrong, one element textelement textelement textName text
.
So, what am I doing wrong? And, is it even possible to use .ChildNodes
and only get the actual child nodes, no deeper?
And, what IS going on here? As I suspect if I understood WHY the bowl of Petunias said that, I would understand the universe better.