1

I have an XML input as shown below:

<?xml version="1.0" encoding="utf-8"?>
 <Content>
    <section name="FileID"/>
    <FileID>109F2AEA-6D9C-4127-963A-9C71D4155C5D</FileID>
       <File Path="C:\test.config">
          <Tag TagName="configuration"/>
       </File>
 </Content>

When I do a recursive search of each node to identify the node with the name "FileID" using the following code line in PowerShell:

if($ConfigChildItem.Name -eq "FileID")
{
    ...
}

where $ConfigChildItem is getting populated with nodes from the XML in recursive to get searched. By this I was expecting to get the Nodes with the name "FileID" like:

<FileID>109F2AEA-6D9C-4127-963A-9C71D4155C5D</FileID>

But it is getting out tags like:

<section name="FileID"/>

since those are having attribute "name" with the value "FileID". How can get only the tags with name "FileID" and not the kind of ones with attribute name as "name" and value of those attributes as "FileID"?

RinoTom
  • 2,278
  • 2
  • 26
  • 40

1 Answers1

1

One of the many ways to do it (using xpath):

$xml = [XML] @'
<?xml version="1.0" encoding="utf-8"?>
 <Content>
    <section name="FileID"/>
    <FileID>109F2AEA-6D9C-4127-963A-9C71D4155C5D</FileID>
       <File Path="C:\test.config">
          <Tag TagName="configuration"/>
       </File>
 </Content>
'@

$expression = "Content/FileID"
$navigator = $xml.PSBase.CreateNavigator()
$node = $navigator.Evaluate($expression)
$node | Select OuterXml # or any other properties

EDIT following your comment:

$xml = [xml](Get-Content "c:\temp\test.xml")
$xml.SelectSingleNode("//FileID")  | ?{ $_.InnerText -eq "109F2AEA-6D9C-4127-963A-9C71D4155C5D" } | %{ $_.InnerText = "blah" }
$xml.Save("c:\temp\test.xml")
David Brabant
  • 41,623
  • 16
  • 83
  • 111
  • Thanks for the answer. This works, but the problem is that, the "FileID" tag can come at any level and that is why I am banking on a recursive search to identify the tag. – RinoTom Jun 01 '12 at 07:24
  • You can use "//FileID" as the xpath expression for finding all FileID at any level. – David Brabant Jun 01 '12 at 07:28
  • But, the search is for editing the content of the output node and saving back the xml file and then this way of extracting the content seperately from the XML input will be tedious. Is there any better way to get this done? – RinoTom Jun 01 '12 at 09:11