[英]Appending to/Removing empty xml nodes using powershell
PowerShell/xml beginner here.... I'm trying to append to or remove empty xml nodes using PowerShell as part of a Nuget Package. 这里的PowerShell / xml初学者....我试图使用PowerShell作为Nuget包的一部分追加或删除空的xml节点。 The xml file has the following format... xml文件具有以下格式......
<Root>
<service name="first">
<item>
</item>
</service>
<service name ="second">
<item>
</item>
</service>
</Root>
First my script select one of the services and save it as a variable, say if the user wants to select service 1..... 首先我的脚本选择其中一个服务并将其保存为变量,如果用户想要选择服务1 .....
if ($xml.Root.service.name -eq $serviceName)
{
$myService = $xml.Root.service
}
Problem is later on, I need to append elements to the node/delete the node... I have something like 问题是稍后,我需要将元素追加到节点/删除节点......我有类似的东西
$newNode = $xml.CreateElement('new'...
.........
$empty = $myService.SelectSingleNode('./item')
$empty.PrependChild($newNode)
But I can't get the this method to work. 但我不能让这种方法起作用。
Any suggestions would be appreciated... 任何建议,将不胜感激...
This should help you out. 这应该可以帮到你。
# 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');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.