且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用bash脚本编辑XML?

更新时间:2023-12-05 21:45:34

您可以使用 xsltproc的命令(从包装 xsltproc的在基于Debian的发行版),与下面的XSLT表:

You can use the xsltproc command (from package xsltproc on Debian-based distros) with the following XSLT sheet:

<?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"/>
  <xsl:param name="tagReplacement"/>
  <xsl:param name="tag1Replacement"/>

  <xsl:template match="node()|@*">
    <xsl:copy>
      <xsl:apply-templates select="node()|@*"/>
    </xsl:copy>

  </xsl:template>
  <xsl:template match="tag">
    <xsl:copy>
      <xsl:value-of select="$tagReplacement"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="tag1">
    <xsl:copy>
      <xsl:value-of select="$tag1Replacement"/>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>

然后使用命令:

xsltproc --stringparam tagReplacement polop \
         --stringparam tag1Replacement palap \
         transform.xsl input.xml

或者你也可以使用正则表达式,但通过正则表达式修改XML是纯粹的邪恶:)

Or you could also use regexes, but modifying XML through regexes is pure evil :)