I'm trying to use the select-xml
cmdlet in Powershell to query some XAML files in my .NET project. Here's what I've tried:
select-xml -content (cat $xaml_file_path) -xpath "//GroupBox"
Where $xaml_file_path
is simply a string containing the file path to the XAML file of interest.
This throws an error:
Select-Xml: Cannot validate argument on parameter 'Content'. The argument is null, empty, or an element of the argument collection contains a null value. Supply a collection that does not contain any null values and then try the command again.
I know the XAML is valid since it compiles fine on Visual Studio. So I'm thinking there might be something else going on here.
Is there a way to query XAML files using Powershell? If so how?
To query an XML (XAML) document that uses namespaces,
Select-Xml
requires you to:[1]declare all the namespaces that any nodes involved in your XPath query are in, via a hashtable that maps self-chosen prefixes to namespace URIs (parameter
-Namespace
).xmlns
), for which a name must be chosen too, but which can not bexmlns
(the example below uses_
).use those self-chosen prefixes for all the nodes referenced in the XPath query (parameter
-XPath
), including those in the default (implied) namespace.A simple example:
If you want to avoid having to deal with namespaces:
In the context of
Select-Xml
(as well as the underlyingSystem.Xml.XmlDocument.SelectNodes()
.NET method), the only way to avoid having to deal with namespaces is to use the*[local-name()='...']
workaround shown in your own answer.In the context of PowerShell's adaption of the
[xml]
DOM, which adds "virtual" properties to instances of[xml]
(System.Xml.XmlDocument
):These properties are always named for the non-prefixed node names; that is, namespaces are effectively ignored.
This is convenient and often sufficient, but it limits you to "drilling down" with dot notation into the document, as opposed to having being able to run XPath queries against the document; for the latter, you can use the
.SelectNodes()
and.SelectSingleNode()
methods, which, however, again necessitate namespace management.[1]The equivalent example with dot notation, building on the same sample file:
[1] The need for namespace management applies analogously to direct use of the underlying
System.Xml.XmlDocument.SelectNodes()
andSystem.Xml.XmlDocument.SelectSingleNodes()
.NET API, although constructing the prefix-to-URI mapping table is a little more cumbersome there - see this answer.