Powershell:
$doc = new-object System.Xml.XmlDocument
$doc.Load($filename)
$items = Select-Xml -Xml $doc -XPath '//item'
$items | foreach {
$item = $_
write-host $item.name
}
I get no output
XML:
<?xml version="1.0" encoding="UTF-8"?>
<submission version="2.0" type="TREE" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:noNamespaceSchemaLocation="TREE.xsd" xmlns="some/kind/of/tree/v1">
<group>
<item></item>
<item></item>
<item></item>
</group>
<submission>
XPath queries are aware of namespaces in an XML document and can use namespace prefixes to qualify element and attribute names. Qualifying element and attribute names with a namespace prefix limits the nodes returned by an XPath query to only those nodes that belong to a specific namespace.
There is no method to connect a namespace prefix to a namespace in XPath. The hosting library can provide these services. It is strongly advised that we take advantage of those features and create namespace prefixes that may be used to qualify XML element and attribute names as needed.
XPath defines a way to compute a string-value for each type of node. Some types of nodes also have names. XPath fully supports XML Namespaces. Thus, the name of a node is modeled as a pair consisting of a local part and a possibly null namespace URI; this is called an expanded-name.
One way to read an XML document in PowerShell is to typecast a variable to the type [xml]. To create this variable, we can use the Get-Content cmdlet to read all of the text in an XML document. To typecast the output of Get-Content we can simply prepend the text [xml] before the variable.
You've got a few problems going on. First you need to specify the namespace in the XPath pattern, the XML isn't well formed (closing tag is not an end tag) and Select-Xml returns XmlInfo and not XmlElement directly. Try this:
$xml = [xml]@'
<submission version="2.0" type="TREE" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:noNamespaceSchemaLocation="TREE.xsd" xmlns="some/kind/of/tree/v1">
<group>
<item></item>
<item></item>
<item></item>
</group>
</submission>
'@
$ns = @{dns="some/kind/of/tree/v1"}
$items = Select-Xml -Xml $xml -XPath '//dns:item' -Namespace $ns
$items | Foreach {$_.Node.Name}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With