【问题标题】:Updating a entry in every section of the xml file更新 xml 文件的每个部分中的条目
【发布时间】:2021-10-27 03:41:02
【问题描述】:

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

【问题讨论】:

  • 我们还没有收到您的来信.. 我的回答解决了您的问题吗?如果是这样,请通过单击左侧的大复选标记图标 来考虑accepting。这将帮助其他有类似问题的人更轻松地找到它。

标签: xml powershell powershell-3.0


【解决方案1】:

示例 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>

【讨论】:

    猜你喜欢
    • 2021-04-19
    • 1970-01-01
    • 2020-04-10
    • 1970-01-01
    • 2020-02-11
    • 2021-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多