1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Powershell]xmlを比較して一致するものを削除

Posted at

複数に散らばるxmlの共通部分を消したい。
PowerShellでdiff的なことができるCompare-Objectは便利だけど、
xmlなんだしそのまま比較して消しゃええやんというわけで書きました

<?xml version="1.0"?>
<hogehoge>
  <fugafuga name="one">いち</message>
  <fugafuga name="two"></message>
 <fugafuga name="three">さん</message>
</hogehoge>
<?xml version="1.0"?>
<hogehoge>
  <fugafuga name="ichi">いち</message>
  <!-- attributeとテキストが一致するこやつだけを消したい! -->
  <fugafuga name="two"></message>
 <fugafuga name="three">スリー</message>
</hogehoge>

こちらごらんください。

function RemoveCommonNodes($targetPath, $commonPath){
    # xmlを取得
    # ちゃんとエンコードは入れましょう、文字化けでエラーを吐きました
    $targetXml = [xml](Get-Content -Encoding UTF8 $targetPath)
    $commonXml = [xml](Get-Content -Encoding UTF8 $commonPath)

    $commonXml.hogehoge.fugafuga | ForEach-Object{
        # いろいろこねくり回しましたが、結局xpathを使うのが書きやすい気がします
        $targetNode = $targetXml.SelectSingleNode("//fugafuga[@name = '$($_.name)']")
        if($targetNode){
            if($targetNode.'#text' -eq $_.'#text')
            {
                # 自分自身を削除
                $targetNode.OwnerDocument.DocumentElement.RemoveChild($targetNode)
            }
        }
    }
    
    # 保存も忘れず
    $targetXml.Save($targetPath)
}

参考

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?