简体   繁体   English

区分标签名称和属性“名称” XML PowerShell

[英]Differentiate Tag Name and attribute “name” XML PowerShell

I have an XML input as shown below: 我有一个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>

When I do a recursive search of each node to identify the node with the name "FileID" using the following code line in PowerShell: 当我对每个节点进行递归搜索以使用PowerShell中的以下代码行来标识名称为“ FileID”的节点时:

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

where $ConfigChildItem is getting populated with nodes from the XML in recursive to get searched. $ ConfigChildItem会以递归方式填充来自XML的节点以进行搜索。 By this I was expecting to get the Nodes with the name "FileID" like: 通过这种方式,我期望获得名称为“ FileID”的节点,例如:

<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". 因为这些文件的属性“名称”的值为“ 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"? 如何仅获取名称为“ FileID”的标签,而不能获取属性名称为“ name”且属性值作为“ FileID”的标签呢?

One of the many ways to do it (using xpath): 执行此操作的多种方法之一(使用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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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