wilx
wilx

Reputation: 18238

How to extract sibling text from XML using XPath?

I have this simple XML document. I want to extact the pairs of ("foo","bar") and ("baz","zab") using, if at all possible, just select-xml. Is it possile and how?

<?xml version="1.0" encoding="UTF-8"?>
<tag>
  <outer>
    <a>foo</a>
    <b>bar</b>
  </outer>
  <outer>
    <a>baz</a>
    <b>zab</b>
  </outer>
</tag>

The problem I am having is that successive invocations of select-xml lose the context of the previous invocation of select-xml and AFAIK the order of nodes returned by it is undefined, so just zipping two lists seems unusable. Or am I wrong that the order of the nodes returned by it is the order in the document?

Upvotes: 0

Views: 326

Answers (1)

JPBlanc
JPBlanc

Reputation: 72660

You can read the file :

$xml = [xml](Get-Content .\test.xml)

And then use :

$xml.tag.outer

Or Like this :

foreach ($outer in $xml.tag.outer)
{
  $outer.a
  $outer.b
}

With Select-Xml :

Clear-Host

$InputText = @"

<?xml version="1.0" encoding="UTF-8"?>   
<tag>   
  <outer>   
    <a>foo</a>   
    <b>bar</b>   
  </outer>   
  <outer>   
    <a>baz</a>   
    <b>zab</b>   
  </outer>   
</tag>
"@ 

$xml = [xml]($InputText)

$nodes = Select-Xml -Xml $xml -XPath "//outer"

foreach ($node in $nodes)
{
 $node.node.a
}

Upvotes: 2

Related Questions