使用xmlstarlet的XPath表达式更新XML。

问题描述 投票:0回答:1

我有一个junit报表XML文件,是这样的。

<?xml version="1.0" encoding="utf-8"?>
<testsuites>
    <testsuite>
        <testcase classname='Formatting Test' name='Test.swift'>
            <failure message='Function parameters should be aligned vertically'>warning: Line:39 </failure>
        </testcase>
        <testcase classname='Formatting Test' name='Test.swift'>
            <failure message='Function parameters should be aligned vertically'>warning: Line:40 </failure>
        </testcase>
    </testsuite>
</testsuites>

我想替换一下内容 <failure> 标签及其 message 属性使用XMLStarlet。我发现一个类似的问题,关于用xpath表达式更新。SO问题

但如果我尝试任何这些命令,

xmlstarlet edit -u '//testsuites/testsuite/testcase/failure' -x '@message/text()' test.xml
xmlstarlet edit -u '//testsuites/testsuite/testcase/failure' -x '@message' test.xml

那么 <failure> 值完全没有了。如果我用这个(只是为了测试)。

xmlstarlet edit -u '//testsuites/testsuite/testcase/failure' -x '../@name' test.xml

结果会是:

<?xml version="1.0" encoding="utf-8"?>
<testsuites>
  <testsuite>
    <testcase classname="Formatting Test" name="Test.swift">
      <failure message="Function parameters should be aligned vertically" name="Test.swift"/>
    </testcase>
    <testcase classname="Formatting Test" name="Test.swift">
      <failure message="Function parameters should be aligned vertically" name="Test.swift"/>
    </testcase>
  </testsuite>
</testsuites>

它附加了 name 归于 <failure> 标签! 真搞不懂xpath是怎么用在 -x 参数。那么如何替换 <failure> 标签的属性值?

xml xpath xmlstarlet
1个回答
1
投票

我想你很接近了,但你选择的是一个属性节点。这就是为什么 name 属性是在上一个命令行示例中添加的。

要使用属性的值,请用以下方法将其转换为字符串 string().

试试这个更新的命令行。

xmlstarlet edit -u '//testsuites/testsuite/testcase/failure' -x 'string(@message)' test.xml

注意:你可能也可以缩短你的 -u 到只是 '//failure'.

© www.soinside.com 2019 - 2024. All rights reserved.