如何删除xml文本所在标签的整个父标签

我想删除如下的整个 <direction> 标签,但是使用后面的代码, 只删除了自身所在标签

<direction placement="above">
<direction-type>
<rehearsal default-x="-20.55" relative-y="30.00" font-weight="bold" font-size="14">ABC</rehearsal>
</direction-type>
</direction>
$test = @'
<?xml version="1.0" encoding="UTF-8"?>
<score-partwise version="3.1">
  <part id="P1">
    <measure number="1" width="118.81">
      <direction placement="above">
        <direction-type>
          <rehearsal default-x="-20.55" relative-y="30.00" font-weight="bold" font-size="14">ABC</rehearsal>
          </direction-type>
        </direction>
      <direction placement="above">
        <direction-type>
          <rehearsal default-x="-40.55" relative-y="60.00" font-weight="bold" font-size="14">CDE</rehearsal>
          </direction-type>
        </direction>
      </measure>
    </part>
  </score-partwise>
'@

[xml]$a = $test

$b = $a.SelectSingleNode("//direction-type/rehearsal[text()='ABC']")

if ($b)
{
    $b.ParentNode.RemoveChild($b)
}

$a.save("ok.xml")
阅读 2k
1 个回答

你的 xpath本来就没有取对啊,你现在的xpath语句是

$b = $a.SelectSingleNode("//direction-type/rehearsal[text()='ABC']")

它表示在direction-type标签下,取text()值为'ABC'rehearsal 子标签,而你期望的其实是取 包含text()值为'ABC'rehearsal 孙子标签 的 direction 标签,所以正确的路径是

$b = $a.SelectSingleNode("//direction-type/rehearsal[text()='ABC']/../../")
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进