更新 xml 文件每个部分的条目

Updating a entry in every section of the xml file

我有这个 xml 文件,我想在其中将“<Department>Sales</Department>" 添加到每个人的标签。我想使用 powershell 添加它并保持格式。任何指针都会有所帮助

之前 :

<employees>
    <person>
         <name>John</name>
         <Age>36</Age>
    </person>
    <person>
         <name>Jack</name>
         <Age>38</Age>
    </person>
    <person>
         <name>Jill</name>
         <Age>34</Age>
    </person>
</employees>

之后:

<employees>
    <person>
         <name>John</name>
         <Age>36</Age>
         <Department>Sales</Department>
    </person>
    <person>
         <name>Jack</name>
         <Age>38</Age>
         <Department>Sales</Department>
    </person>
    <person>
         <name>Jill</name>
         <Age>34</Age>
         <Department>Sales</Department>
    </person>
</employees>

示例 xml 缺少根标记,因此如果我添加:

[xml]$xml = @'
<root>
<employees>
    <person>
         <name>John</name>
         <Age>36</Age>
    </person>
    <person>
         <name>Jack</name>
         <Age>38</Age>
    </person>
    <person>
         <name>Jill</name>
         <Age>34</Age>
    </person>
</employees>
</root>
'@

您可以遍历 employees->person 节点并为每个节点附加一个新节点:

$xml.DocumentElement.employees.person | ForEach-Object {
    $newTag = $xml.CreateElement('Department')
    $newTag.InnerText = 'Sales'
    $_.AppendChild($newTag)
}

输出:

<root>
  <employees>
    <person>
      <name>John</name>
      <Age>36</Age>
      <Department>Sales</Department>
    </person>
    <person>
      <name>Jack</name>
      <Age>38</Age>
      <Department>Sales</Department>
    </person>
    <person>
      <name>Jill</name>
      <Age>34</Age>
      <Department>Sales</Department>
    </person>
  </employees>
</root>