Created
April 12, 2012 05:56
-
-
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
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
<# | |
.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