【问题标题】:how to add value in xml file by using sed [duplicate]如何使用 sed 在 xml 文件中添加值 [重复]
【发布时间】:2018-09-14 21:34:23
【问题描述】:

我这里有xml文件,如下所示

 <?xml version="1.0" encoding="utf-8"?><Application xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Name="fabric:/mytype" xmlns="http://we.xyti.com/2011/01/gone">  <Parameters>
<Parameter Name="mytype" Value="-1" />
<Parameter Name="new1" Value="" />
<Parameter Name="new2" Value="" />
<Parameter Name="new3" Value="" />
<Parameter Name="new4" Value="" /> </Parameters></Application></Application>`

在上面的 xml 中,我需要在每一行中添加值,例如:- 而不是 "" 必须将值作为测试,每个 Name 属性都不同。例如

 <?xml version="1.0" encoding="utf-8"?><Application xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Name="fabric:/mytype" xmlns="http://we.xyti.com/2011/01/gone">  <Parameters>
<Parameter Name="mytype" Value="-1" />
<Parameter Name="new1" Value="test1" />
<Parameter Name="new2" Value="test2" />
<Parameter Name="new3" Value="test3" />
<Parameter Name="new4" Value="test4" /> </Parameters></Application></Application>

【问题讨论】:

  • @WiktorStribiżew 它没有解决我的问题,因为 我需要在每一行的 "" 中添加值 :) - 谢谢您的回复
  • 是的,那么sed -E 's/(enable-welcome-root=")"/\1NEWVALUE"/' file 有什么问题?解决方案就在那里,您只需要删除需要存在值(并将被替换)的[^"]+。在末尾添加g 以替换多次出现:sed -E 's/(enable-welcome-root=")"/\1NEWVALUE"/g' file
  • 我试过 :) 并且在我的情况下,我需要在“”需要添加“测试”的地方添加 @WiktorStribiżew 都将是不同的值
  • 所以在我上面的代码中用test替换NEWVALUE
  • sed -e 's/(Value=")"/\test"/g' "C:\Users\user1\Desktop\test\Cloud.xml" 得到错误 -e 表达式 #1 , char 21: `s 的未知选项 :(

标签: xml sed


【解决方案1】:

有了这个xml文件

<?xml version="1.0" encoding="utf-8"?>
<Application xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://we.xyti.com/2011/01/gone" Name="fabric:/mytype">
  <Parameters>
    <Parameter Name="mytype" Value="-1"/>
    <Parameter Name="new1" Value=""/>
    <Parameter Name="new2" Value=""/>
    <Parameter Name="new3" Value=""/>
    <Parameter Name="new4" Value=""/>
  </Parameters>
</Application>

和xmlstarlet:

xmlstarlet edit -N x="http://we.xyti.com/2011/01/gone" --update '//x:Parameter/@Value' --value "test" file.xml

输出:

<?xml version="1.0" encoding="utf-8"?>
<Application xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://we.xyti.com/2011/01/gone" Name="fabric:/mytype">
  <Parameters>
    <Parameter Name="mytype" Value="test"/>
    <Parameter Name="new1" Value="test"/>
    <Parameter Name="new2" Value="test"/>
    <Parameter Name="new3" Value="test"/>
    <Parameter Name="new4" Value="test"/>
  </Parameters>
</Application>

【讨论】:

    猜你喜欢
    • 2021-03-29
    • 2015-02-07
    • 2014-06-07
    • 2018-06-19
    • 2014-06-26
    • 1970-01-01
    • 2014-12-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多