String parsing of XML text is best avoided, because it is inherently limited and brittle; it's always preferable to use a dedicated XML parser; fortunately, PowerShell provides easy access to .NET's System.Xml.XmlDocument
type ([xml]
):
$xmlText = @'
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://www.sft.com/">a879-956c3452f55e3c</string>
'@
([xml] $xmlText).string.InnerText # .'#text' works too
Note: PowerShell conveniently adapts the XML DOM for dot notation, so that elements and attributes can be accessed as if they were regular object properties - see this answer for more information.
Normally, an XML element that only has text content (a text child node, such as the <string>
element's a879-956c3452f55e3c
value here) directly returns that text content when accessed with dot notation (.string
).
However, because the <string>
element has a namespace declaration (xmlns=...
), .string
actually returns a [System.Xml.XmlElement]
instance whose text child node must explicitly be accessed, either via its .InnerText
property or via the adapted property named for the (generic) node name of the text child element, .'#text'
.