Question

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"?

Was it helpful?

Solution

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")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top