Skip to content

Instantly share code, notes, and snippets.

@JohnLBevan
Created May 15, 2018 10:15
Show Gist options
  • Select an option

  • Save JohnLBevan/ac97bc9e180927804e690d6f202a86f9 to your computer and use it in GitHub Desktop.

Select an option

Save JohnLBevan/ac97bc9e180927804e690d6f202a86f9 to your computer and use it in GitHub Desktop.
Clear-Host
function Extract-XPaths {
[CmdletBinding()]
Param (
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[System.Xml.XmlElement]$elem
)
Process {
[string]$name = $elem.LocalName
$name
$elem.Attributes | ?{($_.Name -ne 'xmlns') -and ($_.Name -notlike 'xmlns:*')} | %{'@{0}' -f $_.Name}
$elem.ChildNodes | ?{$_ -as 'System.Xml.XmlElement'} | Extract-XPaths | %{Join-Path $name $_}
}
}
[xml]$x = @'
<?xml version="1.0" encoding="utf-8"?>
<sch:RootElem xmlns:sch="http://schemas.example.com">
<sch:Demo1>
<sch:ChildElem myAttribute="5">
<sch2:GrandChildElem xmlns:sch2="http://schemas.example.com/2">
<GreatGrandChildElem xmlns="http://schemas.example.com/3">
<Node />
</GreatGrandChildElem>
</sch2:GrandChildElem>
</sch:ChildElem>
</sch:Demo1>
<sch:Demo1>
<sch:Hello />
</sch:Demo1>
<sch:Demo2>
<sch:Hello>World</sch:Hello>
</sch:Demo2>
</sch:RootElem>
'@
$x.DocumentElement | Extract-XPaths
<#
Outputs:
RootElem
RootElem\Demo1
RootElem\Demo1\ChildElem
RootElem\Demo1\@myAttribute
RootElem\Demo1\ChildElem\GrandChildElem
RootElem\Demo1\ChildElem\GrandChildElem\GreatGrandChildElem
RootElem\Demo1\ChildElem\GrandChildElem\GreatGrandChildElem\Node
RootElem\Demo1
RootElem\Demo1\Hello
RootElem\Demo2
RootElem\Demo2\Hello
#>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment