gpt4 book ai didi

powershell - 使用 Powershell 转换 XML - 这个 Sed 命令的等价物是什么?

转载 作者:行者123 更新时间:2023-12-03 01:18:16 25 4
gpt4 key购买 nike

我有以下 XML 片段:

<simpleType name="StatusType">
<restriction base="integer">
<enumeration value="1">
<annotation>
<documentation>Proposed</documentation>
</annotation>
</enumeration>
<enumeration value="2">
<annotation>
<documentation>In Use</documentation>
</annotation>
</enumeration>
</restriction>
</simpleType>


我想转换成:

<simpleType name="StatusType">
<restriction base="integer">
<enumeration value="1" id="Proposed"/>
<enumeration value="2" id="In Use"/>
</restriction>
</simpleType>


我可以使用 Sed 在 Linux 上执行此操作,如下所示:
cat input_file.xml | sed -e '/<enumeration.*[^\/]>/{N;N;N;N;s/\r*\n[ \t]*//g;s/><annotation><documentation>/ id="/;s/<\/documentation><\/annotation><\/enumeration/"\//}'>output_file.xml

我想在 Windows 上实现相同的结果 - 我可以尝试使用 Sed 的 Windows 端口,但我宁愿使用 Powershell 之类的东西。
有什么想法可以在 Powershell 中实现吗? Get-Content 有一个看起来很有用的替换功能 - 我可以做一个非常基础的替换,如下所示:
Get-Content input_file.xml | %{ $_ -replace "enumeration", "replacement_text" }

但我不知道下一步该去哪里。

任何指针将不胜感激,
约翰

最佳答案

我知道您要求 sed 等效项,但是有一个用于操作 XML 的 API,我必须相信这比在 XML 上使用正则表达式更安全。这是执行此操作的一种方法:

$xml = [xml]@'
<simpleType name="StatusType">
<restriction base="integer">
<enumeration value="1">
<annotation>
<documentation>Proposed</documentation>
</annotation>
</enumeration>
<enumeration value="2">
<annotation>
<documentation>In Use</documentation>
</annotation>
</enumeration>
</restriction>
</simpleType>
'@

foreach ($enum in $xml.simpleType.restriction.enumeration) {
[void]$enum.SetAttribute('id', $enum.annotation.documentation.Trim())
[void]$enum.RemoveChild($enum.annotation)
$enum.IsEmpty = $true
}

$xml | Format-Xml

输出:
<simpleType name="StatusType">
<restriction base="integer">
<enumeration value="1" id="Proposed" />
<enumeration value="2" id="In Use" />
</restriction>
</simpleType>

顺便说一句 Format-Xml是来自 PowerShell Community Extensions 的命令模块。您也可以只使用 Save()方法例如:
$xml.Save("C:\foo.xml")

关于powershell - 使用 Powershell 转换 XML - 这个 Sed 命令的等价物是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23529556/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com