【问题标题】:Replacing XML nodes in PowerShell在 PowerShell 中替换 XML 节点
【发布时间】:2011-03-18 22:05:40
【问题描述】:

我有两个 XML 文件(File1.xml、File2.xml)。 File2.xml 是 File1.xml 的子集。

File1.xml 有这样的节点:

<parentnode>
    <item id="GUID1">
         <Text>Some Text</Text> 
    </item>
    <item id="GUID2">
        <Text>Here’s some more text</Text> 
    </item>
</parentnode>

File2.xml 有:

<parentnode>
    <item id="GUID1">
         <Text>Some Replacement Text</Text> 
    </item>
</parentnode>

我想在 File1.xml 中取出 GUIDxitem,并将其替换为 GUIDx 的 item em> 来自 File2.xml。本质上,我想将 File2.xml 中的替换文本插入到 File1.xml 中相应的 item 节点中

如何在 PowerShell 中执行此操作?

【问题讨论】:

    标签: xml powershell


    【解决方案1】:

    假设我在变量$edited 中有第一个xml,在$new 中有第二个。然后您可以通过

    更改ID为GUID1的项目中的值
    $edited.parentnode.item | 
       ? { $_.id -eq 'guid1' } | 
       % { $_.Text = $new.parentnode.item.Text }
    # and save the file
    $edited.Save('d:\File1.xml')
    # see the changes
    gc d:\File1.xml
    

    如果你有更多的项目要替换,你可以使用嵌套管道:

    $edited = [xml]@"
    <parentnode>
        <item id="GUID1"><Text>Some Text</Text></item>
        <item id="GUID2"><Text>Here’s some more text</Text></item>
        <item id="GUID3"><Text>Here’s some more text</Text></item>
        <item id="GUID10"><Text>Here’s some more text</Text></item>
    </parentnode>
    "@
    $new = [xml] @"
    <parentnode>
        <item id="GUID1"><Text>new Guid1</Text></item>
        <item id="GUID2"><Text>new Guid2</Text></item>
        <item id="GUID3"><Text>new Guid3</Text></item>
        <item id="GUID4"><Text>new Guid4</Text></item>
        <item id="GUID5"><Text>new Guid5</Text></item>
    </parentnode>
    "@
    $new.parentnode.item | 
        % { ,($_.id,$_.Text)} | 
        % { $id,$text = $_; 
            $edited.parentnode.item | 
               ? { $_.id -eq $id } | 
               % { $_.Text = $text }
        }
    

    foreach 循环在这里更易读:

    foreach($i in $new.parentnode.item) { 
        $edited.parentnode.item | 
               ? { $_.id -eq $i.Id } | 
               % { $_.Text = $i.Text }
        }
    

    【讨论】:

    • 当我尝试加载我的两个 xml 文件并运行您的代码时,我收到以下错误:“在此对象上找不到属性‘文本’;确保它存在并且是可设置的。”这是我正在运行的代码: $edited = Get-Content file2.xml $new = Get-Content file1.xml $new.parent.item | % { ,($_.id,$_.Text)} | % { $id,$text = $_; $edited.parent.item | ? { $_.id -eq $id } | % { $_.Text = $text } }
    • 加载文件时需要将文本转换为xml:$edited = [xml] (Get-Content file2.xml); $new = [xml] (Get-Content file1.xml)
    • 啊..是的。谢谢!这就是诀窍。不知道我是如何错过 [xml] 的。非常感谢,stej。你的代码就像一个魅力。
    猜你喜欢
    • 2017-10-19
    • 2012-04-13
    • 2014-08-27
    • 1970-01-01
    • 2018-03-05
    • 2013-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多