Search code examples
xmlpowershellparsinginnertext

Innertext not always return the content of the xml element


I'm facing an enoying behaviors with XML parsing in Powershell.

I'm trying to get the content of an XML element but depending if the attribute "type" is set or not the way to get the content is different.

Example:

$xml = [xml] @'
<elem>
    <id type="integer">1</id>
    <name>test</name>
</elem>
'@

$content = $xml.elem.id
Write-Host "content : $content"
$content = $xml.elem.id.InnerText
Write-Host "content: $content"
$content = $xml.elem.name
Write-Host "content: $content"
$content = $xml.elem.name.InnerText
Write-Host "content: $content"

And here is the result:

content: System.Xml.XmlElement
content: 1
content: test
content:

So sometimes I have an XmlElement object and sometime a primitive.

Is there a simple and unique way to have the content of an Xml element ? Or maybe can we say to the XML parser to ignore "type" attribute when parsing ?


Solution

  • Consider using XPath and Select-XML. The result is going to be a match object. Its Node property can be used to access the actual XML element specified by the XPath query. Like so,

    (select-xml '/elem/id' $xml).node."#text"
    # Output
    1
    (select-xml '/elem/name' $xml).node."#text"
    # Output
    test