简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM