RinoTom
RinoTom

Reputation: 2326

Differentiate Tag Name and attribute "name" XML PowerShell

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

Upvotes: 1

Views: 1910

Answers (1)

David Brabant
David Brabant

Reputation: 43539

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

Upvotes: 1

Related Questions