使用powershell追加/删除空xml节点
这里是PowerShell/xml初学者。。。。 我正在尝试使用PowerShell作为Nuget包的一部分来附加或删除空xml节点。xml文件具有以下格式使用powershell追加/删除空xml节点,xml,powershell,nuget,Xml,Powershell,Nuget,这里是PowerShell/xml初学者。。。。 我正在尝试使用PowerShell作为Nuget包的一部分来附加或删除空xml节点。xml文件具有以下格式 <Root> <service name="first"> <item> </item> </service> <service name ="second"> <item>
<Root>
<service name="first">
<item>
</item>
</service>
<service name ="second">
<item>
</item>
</service>
</Root>
问题是稍后,我需要将元素附加到节点/删除节点。。。
我有点像
$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');
这应该对你有所帮助
# 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');
谢谢你,特雷弗。我现在发现xPath方法不起作用的原因是因为xmlns名称空间。你知道如何解决这个问题吗?@Random陌生人你可能会发现这很有帮助->谢谢@Trevor。我现在发现xPath方法不起作用的原因是因为xmlns名称空间。你知道如何解决这个问题吗?@random陌生人你可能会发现这很有帮助->