xml - 使用Powershell附加/删除空xml节点

标签 xml powershell nuget

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/

相关文章:

json - 在powershell中合并两个Json

c# - package.config 更新不更新引用

java - XML 错误 "document is invalid.no grammar found"

android - 如何在 Android XML 中绘制圆弧?

powershell - 如何用 Powershell 替换 Visual Studio 命令提示符?

powershell - 在PowerShell中使用数组删除文件夹?

c# - Nuget 包未找到和/或使用 System.Security.Cryptography

c# - XDocument 或 XmlDocument

sql - 在 SQL Server 中创建嵌套 XML 文件

rest - Partner Central Rest API 401未经授权访问