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

1 Answer 1

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")
Sign up to request clarification or add additional context in comments.

3 Comments

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.
You can use "//FileID" as the xpath expression for finding all FileID at any level.
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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.