Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access an element with xpath with a namespace in powershell?

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>
like image 664
Justin808 Avatar asked Oct 11 '13 01:10

Justin808


People also ask

How does XPath handle namespace?

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.

How do I find the XPath 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.

What is namespace node in XPath?

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.

How do I get the contents of a XML file in PowerShell?

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.


1 Answers

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}
like image 108
Keith Hill Avatar answered Oct 16 '22 15:10

Keith Hill