查看下面的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/