xml - Powershell根据子节点值选择父xml节点并添加子元素

标签 xml powershell xpath xmldocument

查看下面的xml

    <catalog>
        <books>
           <book id="bk101">
              <author>Gambardella, Matthew</author>
              <title>XML Developer's Guide</title>
              <genre>Computer</genre>
              <price>44.95</price>
              <publish_date>2000-10-01</publish_date>
              <description>An in-depth look at creating applications 
              with XML.</description>
           </book>
           <book id="bk102">
              <author>Ralls, Kim</author>
              <title>Midnight Rain</title>
              <genre>Fantasy</genre>
              <price>5.95</price>
              <publish_date>2000-12-16</publish_date>
              <description>A former architect battles corporate zombies, 
              an evil sorceress, and her own childhood to become queen 
              of the world.</description>
           </book>
           <book id="bk103">
              <author>Corets, Eva</author>
              <title>Maeve Ascendant</title>
              <genre>Fantasy</genre>
              <price>5.95</price>
              <publish_date>2000-11-17</publish_date>
              <description>After the collapse of a nanotechnology 
              society in England, the young survivors lay the 
              foundation for a new society.</description>
           </book>
       </books>
    </catalog>

我想在 powershell 中选择作者为 Corets,Eva 的书籍节点/元素,然后添加书籍的子元素,另一个元素(价格的兄弟,直接在价格之后),例如长度。以及新的长度值,例如“456”

因此,在我运行代码后,book 元素的(部分)xml 代码将如下所示:

<catalog>
    <books>
       <book id="bk103">
          <author>Corets, Eva</author>
          <title>Maeve Ascendant</title>
          <genre>Fantasy</genre>
          <price>5.95</price>
          <length>456</length>        
          <publish_date>2000-11-17</publish_date>
          <description>After the collapse of a nanotechnology 
          society in England, the young survivors lay the 
          foundation for a new society.</description>
       </book>
       <book>
        ....
       </book>
    </books>
<etc>

有人可以帮忙吗?已经卡了两天了。谢谢

最佳答案

您可以使用XMLNode.InsertAfter方法。

示例:

[xml]$books = Get-Content .\books.xml
$corets = $books.catalog.books.book | Where-Object { $_.author -eq 'Corets, Eva' }
$coretsPrice = $corets.SelectSingleNode('price')
$coretsLength = $books.CreateElement('length')
$coretsLength.InnerText = 495
$corets.InsertAfter($coretsLength, $coretsPrice)

关于xml - Powershell根据子节点值选择父xml节点并添加子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70005880/

相关文章:

json - Golang 无效字符 'b' 正在寻找值的开头

c# - 为什么 powershell 无法识别 Windows 服务调用的脚本中的 cmdlet?

PHP DOM Xpath 获取图像

python - 用于获取 <p> 内所有数据的 Xpath 表达式

c# - 如何使用 C# 获取 XML 文档的所有子标记名称?

java - 使用 FileInputStream(对于 Java)读取 XML 文件?

android - 如何使用 XML 在视频 View 的顶部添加 Admob 广告?

json - 在powershell中为数组中的每个json对象添加特定属性

regex - 主机文件的正则表达式的行为有所不同

html - 如何在 Xpath 中将两个节点合并为一组?