通过 command-line 合并 xml 标签值

Merge xml tag value by command-line

我正在尝试使用 sed 将出版商和 isbn 值合并到标题标签中。但是我在这里找不到符合我要求的例子。例子如下

来自这个

<book>
  <title>The Big Book of Silly Jokes for Kids</title>
  <publisher>Rockridge Press</publisher>
  <isbn>ISBN-10</isbn>
</book>

至此

<book>
  <title>[Rockridge Press ISBN-10] The Big Book of Silly Jokes for Kids</title>
  <publisher>Rockridge Press</publisher>
  <isbn>ISBN-10</isbn>
</book>

修改XML文件中节点的命令行可以是xmlstarlet,如你所说。

你也可以写一个XSL程序,如下:

book.xsl

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet
  version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes" encoding="utf-8"/>

  <xsl:template match="title"><!-- the node you want to modify -->
    <title>
      <xsl:text>[</xsl:text>
      <xsl:value-of select="../publisher/text()"/>
      <xsl:text> </xsl:text>
      <xsl:value-of select="../isbn/text()"/>
      <xsl:text>] </xsl:text>
      <xsl:value-of select="../title/text()"/>
    </title>
  </xsl:template>

  <xsl:template match="@*|node()"><!-- identity transformation for remaining nodes -->
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>

假设您的原始文件名为 book.xml,上面的 XSL 程序可以在命令行 运行 中调用:

xsltproc book.xsl book.xml

使用 xmlstarlet:

xml ed -u /book/title -x "concat('[',/book/publisher/text(),' ',/book/isbn,'] ',/book/title)" book.xml

输出:

<?xml version="1.0"?>
<book>
  <title>[Rockridge Press ISBN-10] The Big Book of Silly Jokes for Kids</title>
  <publisher>Rockridge Press</publisher>
  <isbn>ISBN-10</isbn>
</book>

编辑:space 在“]”之后添加 '--inplace' 是可选的 'edit file inplace'.