powershell - 如何删除所有 XML 子节点但不删除 Powershell 中的属性

标签 powershell

来自这里:

<products id="col">
  <product code="id1" />
  <product code="id2" />
</products>

我想得到这个:

<products id="col">
</products>

如果我使用 RemoveAll() 它也会删除产品 id 属性,所以我会得到这个

<products>
</products>

这不是我想要的。我可以使用什么方法将我的 id 属性保留在产品节点中?

最佳答案

无需调用 RemoveAll(),您需要找到要删除的节点,然后使用 RemoveChild() 手动删除每个节点:

$XmlDocument = [xml]@'
<products id="col">
  <product code="id1" />
  <product code="id2" />
</products>
'@

$ChildNodes = $XmlDocument.SelectNodes('//product')

foreach($Child in $ChildNodes){
    [void]$Child.ParentNode.RemoveChild($Child)
}

$XmlDocument.Save("C:\path\to\doc.xml")

如果您不知道直接子节点的名称,而只知道父节点名称,您仍然可以使用 XPath 来选择它们:'//ParentNodeName/child::*'

$ChildNodes = $XmlDocument.SelectNodes('//products/child::*')

关于powershell - 如何删除所有 XML 子节点但不删除 Powershell 中的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31504554/

相关文章:

python - virtualenv 挂断了安装 setuptools

powershell - 导出电子邮件地址-删除所有包含数字的电子邮件地址

powershell - ping多台服务器并保存为CSV

powershell - 使用强制选项在Powershell中创建应用程序池

powershell - 从一个 Azure 自动化 Runbook 调用另一个 Azure 自动化 Runbook 时出错

javascript - Powershell西里尔文通过node js输入编码

powershell - 按共性分组

powershell - 获取 SSL 证书 'Issued to'

PowerShell - 格式卷内的 Var

powershell - Select 方法返回类似 @{Name= 的字符串