【问题标题】:Select XML element by attribute value and add an element按属性值选择 XML 元素并添加一个元素
【发布时间】:2014-12-18 19:40:06
【问题描述】:

我有这个结构的 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>

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

<category3 name="Test4"/>

我试过了:

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

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

【问题讨论】:

    标签: xml powershell


    【解决方案1】:

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

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

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

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

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

    【讨论】:

    • [XML]$XML=gc "C:\file.xml" 是加载 xml 的捷径
    猜你喜欢
    • 2012-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-30
    • 1970-01-01
    • 2021-01-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多