Skip to content

Instantly share code, notes, and snippets.

@jstangroome
Created April 12, 2012 00:30
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jstangroome/2363747 to your computer and use it in GitHub Desktop.
Save jstangroome/2363747 to your computer and use it in GitHub Desktop.
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
Copy link

cavo789 commented Feb 6, 2020

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

Works great. 🥇

@TinyToons
Copy link

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