Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Create an XmlNamespaceManager pre-populated with an XML document's namespace prefixes to simplify XPath queries
<#
.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
@cavo789

This comment has been minimized.

Copy link

cavo789 commented Feb 6, 2020

Many thanks Jason. I was googling for this since three hours at least.

Works great. 🥇

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.