繁体   English   中英

使用PowerShell附加/删除空xml节点

[英]Appending to/Removing empty xml nodes using powershell

这里的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');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM