【问题标题】:Powershell - Updating XML Text under Count NodePowershell - 在计数节点下更新 XML 文本
【发布时间】:2020-03-28 10:31:15
【问题描述】:

我有一个类似这样的 XML 文件

<Transactions>
    <Transaction Type="Login">
        <LoginSetting>blahblah</LoginSetting>
    </Transaction>
    <Transaction Type="Search">
        <Parameters>blahblah</Parameters>
        <Count>Setting</Count>
    </Transaction>
    <Transaction Type="Logout">
        <LogoutSetting>blahblah</LogoutSetting>
    </Transaction>
</Transactions>

此文件的路径存储在 $xml_path 下,使用 powershell 我已将这些设置导入 [xml]$xml

[xml]$xml = (get-content $xml_path)

我正在尝试更新“计数”节点下的值

$xml.Transactions.Transaction.Count = 'NewSetting'

由于可以运行 .Count 来获取名为“Transaction”的节点数,因此 powershell 会为我提供此错误输出

'Count' is a ReadOnly property.

还有其他方法可以更新“Count”节点下的值吗?

【问题讨论】:

  • 是的,这是一种“按设计”的错误,您将获得合成“计数”属性的值(即$xml.Transactions.Transaction 中有多少项目)。使用Select-XmlSelectSingleNode() 获取对实际&lt;Count&gt; 节点的引用

标签: xml powershell


【解决方案1】:

这是我的解决方法: 我将 xml 数据导入到两个变量中 - 一个作为平面文本,另一个作为 XML

$xml_flat = (get-content $xml_path)
[xml]$xml = (get-content $xml_path)

我从 xml 变量中提取了“Count”的值(因为它不一定具有显示的“Setting”值)

$count = Select-Xml -XML $xml -XPath "//Count"

我对 flat 变量运行了 .replace 来更新我需要的设置。

$xml_flat = $xml_flat.replace("<Count>$count</Count>","<Count>NewSetting</Count>")

从那里我能够将 $xml_flat 作为 $xml_new 导入到 xml 变量中,并且能够做我需要做的任何其他事情

[xml]$xml_new = $xml_flat

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-24
    • 1970-01-01
    • 2010-10-23
    • 1970-01-01
    相关资源
    最近更新 更多