首页 > 解决方案 > 如何使用 sed 在 xml 文件中添加值

问题描述

我这里有 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>

标签: xmlsed

解决方案


有了这个 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>

推荐阅读