按属性值选择 XML 元素并添加元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26522980/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 12:05:44  来源:igfitidea点击:

Select XML element by attribute value and add an element

xmlpowershell

提问by alexfyren

I have this XML-file with this structure:

我有这个结构的 XML 文件:

<?xml version="1.0" encoding="utf-8"?>
<company>
<category>
    <category1 name="Office1">
        <category2 name="Project1">
            <category3 name="Test1"/>
            <category3 name="Test2"/>
        </category2>
        <category2 name="Project2">
            <category3 name="Test1"/>
            <category3 name="Test2"/>
            <category3 name="Test3"/>
        </category2>
     </category1>

     <category1 name="Office2">
        <category2 name="Project1">
            <category3 name="Test1"/>
            <category3 name="Test2"/>
        </category2>
        <category2 name="Project2">
            <category3 name="Test1"/>
            <category3 name="Test2"/>
            <category3 name="Test3"/>
        </category2>
      </category1>
</category>  
</company>

I want to add a line to company -> category -> category1 "Office2" -> category2 "Project2" The line is:

我想在 company -> category -> category1 "Office2" -> category2 "Project2" 中添加一行,该行是:

<category3 name="Test4"/>

I've tried this:

我试过这个:

$Path = "C:\file.xml"
$xml = [xml](get-content $Path)
$xml.Load($Path)
$test = $xml.company.category
$test.category1 *what to do here*

I know how to do this with one sub-element, and how to clone and add. But I don't know where to start with this one.

我知道如何用一个子元素来做到这一点,以及如何克隆和添加。但我不知道从哪里开始。

回答by Ocaso Protal

Don't know if there is a shorter way, but this should work:

不知道是否有更短的方法,但这应该有效:

$Path = "C:\file.xml"
$xml = [xml](get-content $Path)
$xml.Load($Path)
$target = (($xml.company.category.category1|where {$_.name -eq "Office2"}).category2|where {$_.name -eq "Project2"})
$addElem = $xml.CreateElement("Category3")
$addAtt = $xml.CreateAttribute("name")
$addAtt.Value = "Test4"
$addElem.Attributes.Append($addAtt)
$target.AppendChild($addElem)
$xml.Save("C:\file1.xml")

The main points here are the usage of whereto get the elements with the given attribute values and the creation of a new element and a new attribute.

这里的要点是使用where获取具有给定属性值的元素以及创建新元素和新属性。

Another possible solution to get the "target" element is the usage of XPath:

获取“目标”元素的另一种可能解决方案是使用 XPath:

$target = $xml.SelectSingleNode('//company/category/category1[@name="Office2"]/category2[@name="Project2"]')