【问题标题】:Unable to add node to XML book file using xmlstarlet无法使用 xmlstarlet 将节点添加到 XML 书籍文件
【发布时间】:2021-11-01 18:12:49
【问题描述】:

我正在尝试使用 xmlstarlet 将另一个“修订”节点添加到我的 XML 文件中,但没有成功。这是我的 XML 文件:

<?xml version="1.0" encoding="UTF-8"?>
<book xmlns="http://docbook.org/ns/docbook" xmlns:mw="http://abcxyz.com/namespace/secbook" xmlns:xi="http://www.w3.org/2001/XInclude" xmlns:xlink="http://www.w3.org/1999/xlink" version="5.0-variant secbook5.0" status="some_phase">
  <title><xi:include href="urn:abcxyz:pn:tm_test.xml"><xi:fallback><!-- fallback for tm_test --></xi:fallback></xi:include>Interface Reference</title>
  <info>
    <productname>
      <xi:include href="urn:abcxyz:pn:tm_test.xml">
        <xi:fallback>
          <!-- fallback for tm_test -->
        </xi:fallback>
      </xi:include>
    </productname>
    <releaseinfo>
      <xi:include href="urn:abcxyz:pn:this_release_name.xml">
        <xi:fallback>
          <!-- fallback for this_release_name -->
        </xi:fallback>
      </xi:include>
    </releaseinfo>
    <revhistory>
      <revision>
        <revnumber>Online</revnumber>
        <date>July 2021</date>
        <revremark>Version 2.3</revremark>
      </revision>
      <revision>
        <revnumber>Online</revnumber>
        <date>Jan 2022</date>
        <revremark>Version 2.4</revremark>
      </revision>
    </revhistory>
    <biblioid class="pubsnumber">interface_ref</biblioid>
    <subjectset>
      <subject>
        <subjectterm>SOMETERM</subjectterm>
      </subject>
    </subjectset>
  </info>
  </book>

这是我迄今为止尝试过的:

xmlstarlet edit -s /book/info/revhistory --type elem --name revisionTMP --value "" \
            -s /book/info/revhistory/revisionTMP --type elem --name revnumber  --value "Online" \
            -s /book/info/revhistory/revisionTMP --type elem --name date  --value "Jul 2022" \
            -s /book/info/revhistory/revisionTMP --type elem --name revremark  --value "Version 2.5" \
            -r /book/info/revhistory/revisionTMP -v revision \
           ./test_book.xml

虽然此代码适用于像这样的一个更简单的 XML 文件,我已经能够成功地添加一个新的“学生”,但它在较大的“test_book.xml”文件上却失败了。我错过了什么?我对不涉及xmlstartlet 的其他优雅解决方案持开放态度。

<?xml version="1.0"?>
<Students>
  <student>
    <name>john</name>
    <id>123</id>
  </student>
  <student>
    <name>mike</name>
    <id>234</id>
  </student>
</Students>

我将 xmlstarlet 命令放在了 s shell 脚本中。脚本执行,但没有任何变化。

【问题讨论】:

  • 我缺少什么?您的文件使用命名空间。
  • 那么我如何让它与命名空间一起工作?
  • @Cyrus 根据您的建议,我这样做了:xmlstarlet edit -s "//_:revhistory" --type elem --name revisionTMP --value ""\ -s "//_:revhistory/revisionTMP" --type elem --name revnumber --value "Online" \ 等。这行得通。我的解决方案稳健吗?
  • XSLT 转换是将一种 XML 转换成另一种 XML 的最佳方式。

标签: xml xml-namespaces xmlstarlet


【解决方案1】:

您是否包含选项-L 来实际编辑文件?

来自xmlstarlet ed --help

-L (or --inplace) - edit file inplace

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-27
    相关资源
    最近更新 更多