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

时间:2014-10-23 07:13:47

标签: 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>

我想在公司添加一行 - &gt;类别 - &gt; category1&#34; Office2&#34; - &GT; category2&#34; Project2&#34; 该行是:

<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*

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

2 个答案:

答案 0 :(得分:24)

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

$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来获取具有给定属性值的元素以及创建新元素和新属性。

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

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

答案 1 :(得分:0)

const keys = Object.keys(this.state.items);
let items = this.state.items;
for (let i = 0; i < keys.length; i++) {
  items[keys[i]] = {
    ...items[keys[i]],
    active: true
  };
}

this.setState({ items });

是加载xml的简短方法

相关问题