【问题标题】:Mass XML Editing using command line tools使用命令行工具进行海量 XML 编辑
【发布时间】:2013-02-19 15:03:29
【问题描述】:

我有数百个 xml 文件,我想在特定位置进行一次性编辑。在每个 xml 文件的某处,我都有类似这样的内容。

   <SomeTag
     attribute1 = "foo"
     attribute2 = "bar"
     attribute3 = "lol"/>

属性的数量和名称会根据文件而变化,但SomeTag 不会。我想在最后一个属性之后添加另一个属性。

我意识到以这种方式编辑 xml 很愚蠢,但这只是一项临时工作,我想用 sed 之类的东西来做,但我不知道多行的用法。

【问题讨论】:

    标签: linux command-line sed awk


    【解决方案1】:

    我会使用转换样式表和标识模板 (XSLT)。

    <xsl:template match="@*|node()">
      <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
      </xsl:copy>
    </xsl:template>
    <xsl:template match="SomeTag">
      <xsl:copy>
        <xsl:attribute name="newAttribute">
          <xsl:value-of select="'whatever'"/>
        </xsl:attribute>
        <xsl:apply-templates select="@*|node()"/>
      </xsl:copy>
    </xsl:template>
    

    这将复制整个 XML,但会运行为您的“SomeTag”定义的模板。

    取自here

    【讨论】:

      【解决方案2】:

      你可以使用 XML shell xsh:

      for my $file in { glob "*.xml" } {
          open $file ;
          for //SomeTag set @another 'new value' ;
          save :b ;
      }
      

      【讨论】:

        【解决方案3】:

        如果您的输入文件真的那么简单且格式一致:

        $ cat file
        foo
           <SomeTag
             attribute1 = "foo"
             attribute2 = "bar"
             attribute3 = "lol"/>
        bar
        
        $ gawk -v RS='\0' -v ORS= '{sub(/<SomeTag[^/]+/,"&\n     attribute4 = \"eureka\"")}1' file
        foo
           <SomeTag
             attribute1 = "foo"
             attribute2 = "bar"
             attribute3 = "lol"
             attribute4 = "eureka"/>
        bar
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-06-17
          • 2011-01-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-03-04
          • 1970-01-01
          • 2012-10-05
          相关资源
          最近更新 更多