看下面的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”
因此,在我運行代碼后,書本元素的(部分)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>
任何人都可以提供幫助嗎?卡了兩天了。謝謝
uj5u.com熱心網友回復:
您可以使用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)
uj5u.com熱心網友回復:
您可以使用以下 XPath 運算式僅選擇<book />子節點<author>的文本值為 的節點Corets, Eva:
//book[author[. = 'Corets, Eva']]
所以你可以這樣做:
# Create a new XML document
$newDocument = [xml]'<catalog><books></books></catalog>'
$newBooks = $newDocument.SelectSingleNode('/catalog/books')
# Loop through all relevant <book> nodes in the existing document
foreach($book in $existingDocument.SelectNodes('//book[author[. = 'Corets, Eva']]')){
# import book node to new document
$newBook = $newDocument.ImportNode($book, $true)
# add new required child node
$newLength = $newDocument.CreateElement('length')
$newLength.InnerText = '456'
# insert new node after `price`
[void]$newBook.InsertAfter($newLength, $newBook.SelectSingleNode('./price'))
# insert new book node under /catalog/books
[void]$newBooks.AppendChild($newBook)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/359588.html
