Skip to content

Instantly share code, notes, and snippets.

@jstangroome
Created April 12, 2012 05:56
Show Gist options
  • Save jstangroome/2364844 to your computer and use it in GitHub Desktop.
Save jstangroome/2364844 to your computer and use it in GitHub Desktop.
An alternate version of another gist ( https://gist.github.com/2363747 ) but to be used with PowerShell's Select-Xml instead
<#
.EXAMPLE
Select-NamespacedXml -XPath //def:SomeElement -XmlDocument $XmlDoc -DefaultNamespacePrefix def
.EXAMPLE
Select-NamespacedXml -XPath //foo:AFooElement -XmlDocument $XmlDoc
Assuming the document looks like this:
<Root xmlns="http://namespaces/vanilla" xmlns:foo="http://namespaces/foo">
<foo:AFooElement>Hello</foo:AFooElement>
<SomeElement>Bye</SomeElement>
</Root>
Achieving the same results with PowerShell's default Select-Xml would require this:
Select-Xml -XPath //foo:AFooElement -Xml $XmlDoc -Namespace @{ foo = 'http://namespaces/foo' }
#>
[CmdletBinding()]
param (
[Parameter(Mandatory=$true, Position=0)]
[string]
$XPath,
[Parameter(Mandatory=$true, Position=1)]
[xml]
$XmlDocument,
[string]
$DefaultNamespacePrefix
)
$Namespace = @{}
$DefaultNamespace = $XmlDocument.DocumentElement.GetAttribute('xmlns')
if ($DefaultNamespace -and $DefaultNamespacePrefix) {
$Namespace.Add($DefaultNamespacePrefix, $DefaultNamespace)
}
$XmlDocument.DocumentElement.Attributes |
Where-Object { $_.Prefix -eq 'xmlns' } |
ForEach-Object {
$Namespace.Add($_.LocalName, $_.Value)
}
Select-Xml -XPath $XPath -Xml $XmlDocument -Namespace $Namespace
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment