Search code examples
xmlpowershell

XmlElement .HasChildElement


Given XML of

<Element>Text</Element>

and

<Element>
    <Child>Text</Child>
</Element>

Is there an easy way to differentiate the one that has a Child Element vs just Text, which is a Child Node? $xmlElement.HasChildNodes will return True for both. I can play games with $xmlElement.ChildNodes.Where({($_.NodeType -eq 'Element')}) but that is anything but elegant. What I really want is $xmlElement.HasChildElements but that doesn't seem to be an option, and trying to extend [Xml.XmlElement] in PowerShell is pretty miserable. I feel like the only option is to loop through all the child nodes and look for .NodeType -eq 'Element' and a count of 0 on that collection. But it feels like something that would be really common to need to do and thus have an easy way to do.


Solution

  • Try using xpath; something like:

    $nodes = $xml.SelectNodes("//Element[descendant::*]");
    
    foreach($node in $nodes) {
        echo $node.OuterXml
        }
    

    The output should be only:

    <Element><Child>Text2</Child></Element>