To fetch the value of an XML element in powershell, we can simply write out the path by treating the elemnts as if they were properties of a PowerShell object; i.e. $xml.RootElement.ChildElement.GrandChild
.
However, if the element we're interested in has an attribute associated, to get the text value we need to drill down to the text node; i.e. $xml.RootElement.ChildElement.GrandChild.'#text'
.
Sadly when the element doesn't have an attribute, we can't use the text node; i.e. in that scenarion, $xml.RootElement.ChildElement.GrandChild.'#text'
does not work.
Clear-Host
$example = [xml](@"
<demo>
<element attribute='1'>10</element>
<element>20</element>
</demo>
"@)
"just the element"
$example.demo.element
"element's text"
$example.demo.element.'#text'
I've written a nasty workaround for this, but suspect that's the wrong approach / that PowerShell has a more elegant way to resolve this issue.
My Nasty Workaround:
function Get-TextNode {
[CmdletBinding()]
param (
[Parameter(ValueFromPipeline = $true)]
$xmlElement
)
process {
if($xmlElement.Attributes.Count -eq 0) {
$xmlElement
} else {
$xmlElement.'#text'
}
}
}
$example.demo.element | Get-TextNode