-
Notifications
You must be signed in to change notification settings - Fork 29
/
Resolve-XmlSchemaLocation.ps1
76 lines (67 loc) · 2.29 KB
/
Resolve-XmlSchemaLocation.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
<#
.SYNOPSIS
Gets the namespaces and their URIs and URLs from a document.
.INPUTS
System.Xml.XmlDocument or System.String containing the path to an XML file.
.OUTPUTS
System.Management.Automation.PSCustomObject for each namespace, with Path,
Node, Alias, Urn, and Url properties.
.FUNCTIONALITY
XML
.LINK
https://www.w3.org/TR/xmlschema-1/#schema-loc
.LINK
https://stackoverflow.com/a/26786080/54323
.EXAMPLE
Resolve-XmlSchemaLocation.ps1 test.xml
Path : C:\test.xml
Node : root
Alias : xml
Urn : http://www.w3.org/XML/1998/namespace
Url :
Path : C:\test.xml
Node : root
Alias : xsi
Urn : http://www.w3.org/2001/XMLSchema-instance
Url :
#>
#Requires -Version 3
[CmdletBinding()][OutputType([Management.Automation.PSCustomObject])] Param(
# The string to check.
[Parameter(ParameterSetName='Xml',Position=0,Mandatory=$true,ValueFromPipeline=$true)][xml] $Xml,
# A file to check.
[Parameter(ParameterSetName='Path',Position=0,Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[Alias('FullName')][ValidateScript({Test-Path $_ -PathType Leaf})][string] $Path
)
Process
{
$xmlsrc = if($Path) {@{Path=$Path}} else {@{Xml=$Xml}}
foreach($element in (Select-Xml '//*[@xsi:schemaLocation]' @xmlsrc -Namespace @{
xsi='http://www.w3.org/2001/XMLSchema-instance'} |Select-Object -ExpandProperty Node))
{
$nonsatt = $element.Attributes.GetNamedItem('noNamespaceSchemaLocation',
'http://www.w3.org/2001/XMLSchema-instance')
$nons = if($nonsatt) {$nonsatt.Value}
[string[]]$locations = $element.Attributes.GetNamedItem('schemaLocation',
'http://www.w3.org/2001/XMLSchema-instance').Value.Trim() -split '\s+'
if($locations.Length -band 1) {Write-Warning "XML schemaLocation has $($locations.Length) entries"}
$schemaLocation = @{}
for($i = 1; $i -lt $locations.Length; $i += 2)
{
$schemaLocation[$locations[$i-1]] = $locations[$i]
}
$nav = $element.CreateNavigator()
[void]$nav.MoveToFollowing('Element')
$ns = $nav.GetNamespacesInScope('All')
foreach($ns in $ns.GetEnumerator())
{
[pscustomobject]@{
Path = $Path
Node = $element
Alias = $ns.Key
Urn = $ns.Value
Url = if($schemaLocation.ContainsKey($ns.Value)) {$schemaLocation[$ns.Value]} else {$nons}
}
}
}
}