我需要向XML中的现有节点添加一个新元素。当前的结构基本上是这样的:
<CommandManagerResults>
<ListReports>
<Row>
<Name>aaa</Name>
</Row>
<Row>
<Name>bbb</Name>
</Row>
</ListReports>
<ListDocuments>
<Row>
<Name>ccc</Name>
</Row>
<Row>
<Name>ddd</Name>
</Row>
</ListDocuments>
</CommandManagerResults>
我需要在所有的"行"中添加一个元素节点。到目前为止,我得到的代码是:
$directory = "E:temp"
cd $directory
[xml]$XmlDocument = Get-Content ".test.xml"
$ProjectName = $XmlDocument.CreateElement("ProjectName")
$ProjectName.InnerText = "test"
$temp = $XmlDocument.SelectNodes("//Row")
foreach ($row in $temp){
$row.AppendChild($ProjectName)
$XmlDocument.Save($directory + 'test.xml')
}
然而,只有最后一行"节点被保存为新的ProjectName"元素。我在foreach循环中添加了"$row | FL",它显示每一行都有ProjectName元素,因为通过循环的每次迭代都有,不幸的是,无论我是否保存在foreach循环内部或之后,只有最后一行节点与ProjectName元素保存。结果如何:
<CommandManagerResults>
<ListReports>
<Row>
<Name>aaa</Name>
</Row>
<Row>
<Name>bbb</Name>
</Row>
</ListReports>
<ListDocuments>
<Row>
<Name>ccc</Name>
</Row>
<Row>
<Name>ddd</Name>
<ProjectName>Test</ProjectName>
</Row>
</ListDocuments>
</CommandManagerResults>
我希望最后的结构是什么样子:
<CommandManagerResults>
<ListReports>
<Row>
<Name>aaa</Name>
<ProjectName>Test</ProjectName>
</Row>
<Row>
<Name>bbb</Name>
<ProjectName>Test</ProjectName>
</Row>
</ListReports>
<ListDocuments>
<Row>
<Name>ccc</Name>
<ProjectName>Test</ProjectName>
</Row>
<Row>
<Name>ddd</Name>
<ProjectName>Test</ProjectName>
</Row>
</ListDocuments>
</CommandManagerResults>
仅供参考,我对Powershell和xml非常陌生,所以希望我所说的一切都是有意义的,至少我正在朝着正确的方向前进。
您必须为要添加的每个元素创建一个新元素。最后,Save()
调用应该只在文档结束时进行。
$temp = $XmlDocument.SelectNodes("//Row")
foreach ($row in $temp){
$ProjectName = $XmlDocument.CreateElement("ProjectName")
$ProjectName.InnerText = "test"
$row.AppendChild($ProjectName)
}
$XmlDocument.Save($directory + 'test.xml')
在侧面说明[xml]$XmlDocument = Get-Content ".test.xml"
,虽然方便,是不好的做法。它的工作只是偶然的,因为现在大多数XML文档都是UTF-8编码的,这恰好是Get-Content
使用的默认编码。但是Get-Content
对XML"编码"的实际值一无所知;属性。
加载XML文档的正确方式,同时尊重其"编码";属性:
$xml = [xml]::new()
$xml.Load((Convert-Path ".test.xml"))