Powershell:删除Xml元素失败

时间:2015-07-06 10:42:08

标签: xml powershell removechild

我有一个xml文件,其中包含多个图书名称:

<?xml version="1.0" encoding="utf-8"?>
<Project>
  <ItemGroup>
    <Book Name="Learn Powershell" />
    <Book Name=".net Programming" />
    <Book Name="C# Programming" />
  </ItemGroup>
</Project>

然后我有一个powershell脚本,试图找出包含“powershell”的书名并将其从xml中删除:

[xml]$xml=Get-Content "D:\m.xml"
$p = $xml.Project.ItemGroup.Book
$node=$p|?{$_.Name.Contains("Powershell")}
$node.Parent.RemoveChilde($node)

报告运行时异常:

PS D:\> D:\Untitled4.ps1
You cannot call a method on a null-valued expression.
At D:\Untitled4.ps1:4 char:1
+ $node.Parent.RemoveChild($node)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull

为什么呢?如何更正我的代码?

1 个答案:

答案 0 :(得分:1)

应为$node.ParentNode.RemoveChild($node)