【问题标题】:How to partially pretty print XML files from the command line?如何从命令行部分漂亮地打印 XML 文件?
【发布时间】:2016-02-06 23:37:44
【问题描述】:

我正在编写一个 unix shell 脚本,我需要在其中漂亮地打印 XML 文件, 但问题是它们的某些部分我可能不会碰。 即,它们是包含在 XML 中的 Apache Jelly 脚本 我需要漂亮打印的文件。所以我需要转换这个

<proc source="customer"><scriptParam value="_user"/><scriptText><jelly:script>

  <jelly:log level="info">
    this text needs
      to keep its indent level
        and this is none of my business
  </jelly:log>

  <!-- get date -->
  <sql:query var="rs"><![CDATA[
    select sysdate
    from dual
  ]]></sql:query>

</jelly:script>
</scriptText></proc>

进入这个

<proc source="customer">
  <scriptParam value="_user"/>
  <scriptText>
<jelly:script>

  <jelly:log level="info">
    this text needs
      to keep its indent level
        and this is none of my business
  </jelly:log>

  <!-- get date -->
  <sql:query var="rs"><![CDATA[
    select sysdate
    from dual
  ]]></sql:query>

</jelly:script>
  </scriptText>
</proc>

请注意,jelly:script 元素的唯一更改是换行符 在它之前。

我在 xmllintxmlstarlet 中找不到任何选项来忽略 某种元素。有什么工具可以帮助我实现这一目标吗?我上线了 Linux,如果重要的话。

【问题讨论】:

  • “但问题是它们的某些部分我可能无法触及。” - 我认为这不符合 xmlstarletxmllint 以及可能大多数基于 XML 解析器的工具的资格。否则我会有suggested xmlstarlet ed

标签: xml shell formatting xmlstarlet xmllint


【解决方案1】:

当要求 inside 元素 jelly:script 没有空格可以改变,那么你可以使用xml_pp(在安装了perl包perl-XML-Twig的linux上。选项-p some-element可以是用于保留这些元素内的所有空格:

xml_pp -p jelly:script  thefile.xml

这将创建这个:

<proc source="customer">
  <scriptParam value="_user"/>
  <scriptText>
    <jelly:script>

  <jelly:log level="info">
    this text needs
      to keep its indent level
        and this is none of my business
  </jelly:log>

  <!-- get date -->
  <sql:query var="rs"><![CDATA[
    select sysdate
    from dual
  ]]></sql:query>

</jelly:script>
  </scriptText>
</proc>

如您所见,起始元素&lt;jelly:script&gt; 也是缩进的,因为添加的空格仍在元素之外。

如果这也被禁止,那么您必须选择更高的级别 (scriptText),或者将其通过管道传递给再次删除这些空格的命令:

xml_pp -p jelly:script thefile.xml | perl -pe 's/^\s*(<jelly:script>)/$1/'

【讨论】:

    猜你喜欢
    • 2013-04-12
    • 2013-12-14
    • 2015-01-12
    • 2010-09-13
    • 1970-01-01
    • 1970-01-01
    • 2010-09-05
    • 1970-01-01
    • 2012-10-08
    相关资源
    最近更新 更多