Create an XmlNamespaceManager pre-populated with an XML document's namespace prefixes to simplify XPath queries
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<# | |
.DESCRIPTION | |
Create an XmlNamespaceManager pre-populated with an XML document's namespace prefixes to simplify XPath queries | |
.PARAMETER XmlDocument | |
An instance of [xml] with custom namespaces to register in the XmlNamespaceManager. | |
.PARAMETER DefaultNamespacePrefix | |
Optional prefix to use for the default namespace in XPath queries. | |
.EXAMPLE | |
$NsMgr = New-XmlNamespaceManager -XmlDocument $XmlDoc -DefaultNamespacePrefix def | |
This then enables nodes in the default namespace to be queries using the 'def' prefix: | |
$XmlDoc.SelectNodes('//def:SomeElement', $NsMgr) | |
.EXAMPLE | |
$NsMgr = New-XmlNamespaceManager -XmlDocument $XmlDoc | |
Assuming the document's root element declares namespaces with prefixes like this: | |
<Root xmlns:foo="http://namespaces/foo"> | |
Then nodes in the 'http://namespaces/foo' namespace can be queried by the prefix: | |
$XmlDoc.SelectNodes('//foo:AFooElement', $NsMgr) | |
#> | |
[CmdletBinding()] | |
param ( | |
[Parameter(Mandatory=$true, Position=0)] | |
[xml] | |
$XmlDocument, | |
[string] | |
$DefaultNamespacePrefix | |
) | |
$NsMgr = New-Object -TypeName System.Xml.XmlNamespaceManager -ArgumentList $XmlDocument.NameTable | |
$DefaultNamespace = $XmlDocument.DocumentElement.GetAttribute('xmlns') | |
if ($DefaultNamespace -and $DefaultNamespacePrefix) { | |
$NsMgr.AddNamespace($DefaultNamespacePrefix, $DefaultNamespace) | |
} | |
$XmlDocument.DocumentElement.Attributes | | |
Where-Object { $_.Prefix -eq 'xmlns' } | | |
ForEach-Object { | |
$NsMgr.AddNamespace($_.LocalName, $_.Value) | |
} | |
return ,$NsMgr # unary comma wraps $NsMgr so it isn't unrolled |
A Huge thank you Jason! You made may day!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Many thanks Jason. I was googling for this since three hours at least.
Works great.🥇