PowerShell / xml初学者在这里...
我正在尝试使用PowerShell作为Nuget软件包的一部分附加或删除空的xml节点。 xml文件具有以下格式...
<Root>
<service name="first">
<item>
</item>
</service>
<service name ="second">
<item>
</item>
</service>
</Root>
首先,我的脚本选择一个服务并将其保存为变量,例如,如果用户要选择服务1....。
if ($xml.Root.service.name -eq $serviceName)
{
$myService = $xml.Root.service
}
问题稍后,我需要将元素追加到节点/删除节点...
我有类似的东西
$newNode = $xml.CreateElement('new'...
.........
$empty = $myService.SelectSingleNode('./item')
$empty.PrependChild($newNode)
但是我无法使用这种方法。
任何建议,将不胜感激...
最佳答案
这应该可以帮助您。
# Get an XML document
$MyXml = [xml]'<?xml version="1.0" encoding="utf-8"?><root><service name="foo"><item></item></service></root>';
# Create a new element from the XmlDocument object
$NewElement = $MyXml.CreateElement('new');
# Select the element that we're going to append to
$ServiceElement = Select-Xml -Xml $MyXml -XPath '/root/service[@name="foo"]/item';
# Append the 'new' element to the 'item' element
$ServiceElement.AppendChild($NewElement);
# Echo the OuterXml property of the $MyXml variable to verify changes
Write-Host -Object $MyXml.OuterXml;
# Save the XML document
$MyXml.Save('c:\test.xml');
关于xml - 使用Powershell附加/删除空xml节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10728132/