Keith
Keith

Reputation: 281

How to select an XmlElement based on an attribute value?

Say I have the following xml

<?xml version="1.0"?>
<catalog>
   <book id="bk101">
      <author>Gambardella, Matthew</author>      
   </book>
   <book id="bk102">
      <author>Ralls, Kim</author>
   </book>
   <book id="bk103">
      <author>Corets, Eva</author>     
   </book>
</catalog>

I have an xmlNode representing the whole file which I read in from a file by doing

$myXml=New-Object XML
$myXml.Load("path to the books file")

How do I then select the book element which has the id value of "bk102" so I can then pass that Xmlnode off to another function expecting an XMlNode?

i.e my new node would be :

$Node = <book id="bk102">
       <author>Ralls, Kim</author>
    </book>

Thanks all. Been struggling all morning.

Upvotes: 8

Views: 15862

Answers (1)

Frode F.
Frode F.

Reputation: 54821

You could filter the books using Where-Object, or you could try XPath. Here's two examples:

Dot-navigation

$bookid = 'bk102'
$myxml = [xml](Get-Content '.\New Text Document.txt')

$node = $myxml.catalog.book | Where-Object { $_.id -eq $bookid }
$node

id                                                         author
--                                                         ------
bk102                                                      Ralls, Kim

XPath

$bookid = 'bk102'
$myxml = [xml](Get-Content '.\New Text Document.txt')

$node = $myxml.SelectSingleNode("catalog/book[@id='$bookid']")
$node

id                                                         author
--                                                         ------
bk102                                                      Ralls, Kim

Upvotes: 20

Related Questions