我正在努力在 Powershell 中將子節點遞回添加到 XML。主要目標是根據提供的檔案更新 XML 檔案。
前任。XML 看起來像這樣:
<a>
<b>
<c1>Value0</c1>
</b>
</a>
我想添加帶有子節點的節點,使其看起來像這樣(順序并不重要):
<a>
<b>
<c>
<d1>Value1</d2>
<d2>Value2</d2>
<d3>Value3</d3>
</c>
<c1>Value0</c1>
</b>
</a>
我為此創建了兩個函式:
function InsertRecursively {
param (
$OriginalXml,
$DataToInsert
)
foreach ($key in $DataToInsert.Keys) {
if ($DataToInsert.$key.GetType().Name -eq "Hashtable") {
SetChildItem -XML $OriginalXml -ChildName $key
InsertRecursively -OriginalXml $OriginalXml.$key -DataToInsert $DataToInsert.$key
}
else {
SetChildItem -Xml $OriginalXml -ChildName $key -ChildValue $DataToInsert.$key
}
}
}
function SetChildItem {
param (
$Xml,
$ChildName,
$ChildValue
)
if ($null -eq $Xml.$ChildName) {
$child = $ssCont.CreateElement($ChildName)
if ($ChildValue) {
$child.InnerText = $ChildValue.ToString()
}
$Xml.AppendChild($child) > $null
Write-Host "Adding item '$ChildName'"
}
elseif (($null -ne $ChildValue) -and ($Xml.$ChildName -ne $ChildValue)) {
$Xml.$ChildName = $ChildValue.ToString()
Write-Host "Updating value of item '$ChildName'"
}
else {
Write-Host "Item '$ChildName' is set correctly"
}
return $Xml
}
當函式將第一個子節點添加到現有節點時一切正常,問題是當函式想要將另一個子節點添加到該子節點時 - SetChildItem 函式中的 $Xml 引數只是一個空字串,而不是函式可以添加一個孩子。結果是字串不包含 AppendChild 方法的錯誤。
uj5u.com熱心網友回復:
像下面這樣更簡單的東西:
$xml = [xml]@"
<a>
<b>
<c1>Value0</c1>
</b>
</a>
"@
$newElements = [xml]@"
<c>
<d1>Value1</d1>
<d2>Value2</d2>
<d3>Value3</d3>
</c>
"@
$newNode = $xml.ImportNode($newElements.get_DocumentElement(), $true)
$xml.SelectSingleNode('//b').AppendChild($newNode)
應該輸出
<a>
<b>
<c1>Value0</c1>
<c>
<d1>Value1</d1>
<d2>Value2</d2>
<d3>Value3</d3>
</c>
</b>
</a>
uj5u.com熱心網友回復:
這是我在 C# 中使用 Xml Linq 的方法。您可以將 Xml Linq 庫與 Power Shell 一起使用。
string input = @"
<a>
<b>
<c1>Value0</c1>
</b>
</a>";
XDocument doc = XDocument.Parse(input);
XElement nodeB = doc.Descendants("b").FirstOrDefault();
XElement nodeC = new XElement("c", new object[] {
new XElement("d1", "Value1"),
new XElement("d2", "Value2"),
new XElement("d2", "Value3")
});
nodeB.Add(nodeC);
如果您希望新節點作為第一項使用: nodeB.AddFirst(nodeC);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/448949.html
下一篇:C:列印反向鏈表
