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

ale*_*ren 17 xml powershell

我有这个结构的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>
Run Code Online (Sandbox Code Playgroud)

我想为公司添加一行 - >类别 - > category1"Office2" - > category2"Project2"该行是:

<category3 name="Test4"/>
Run Code Online (Sandbox Code Playgroud)

我试过这个:

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

我知道如何使用一个子元素,以及如何克隆和添加.但我不知道从哪里开始.

Oca*_*tal 26

不知道是否有更短的方式,但这应该工作:

$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")
Run Code Online (Sandbox Code Playgroud)

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

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

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