【发布时间】:2014-05-07 22:25:14
【问题描述】:
我有以下 XML sn-p:
<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>
我可以在 Linux 上使用 Sed 执行此操作,如下所示:
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 上实现相同的结果 - 我可以尝试使用 Windows 端口的 Sed,但我更愿意使用 Powershell 之类的东西。 有什么想法可以在 Powershell 中实现吗? Get-Content 有一个看起来很有用的替换功能 - 我可以做一个非常基础的替换,如下所示:
Get-Content input_file.xml | %{ $_ -replace "enumeration", "replacement_text" }
但我不知道下一步该去哪里。
任何指针将不胜感激, 约翰
【问题讨论】:
-
好吧,既然你似乎可以用正则表达式替换,你可以只做
(Get-Content .\data.xml -Raw) -replace '(?s)(<enumeration value="[^"]*")[^>]*>.*?<documentation>([^<]*)</documentation>.*?</enumeration>', '$1 id="$2"/>'。如果您想感受一点额外的熟悉感(或者只是想感受一点猫的感觉),您可以使用cat别名而不是Get-Content。 -
太好了,对我有用,感谢您抽出宝贵时间回答。
标签: powershell