Можно ли комментировать / раскомментировать теги внутри xml-файла, используя xmlstarlet или другие инструменты bash? - PullRequest
0 голосов
/ 06 июня 2018

Как я могу прокомментировать / раскомментировать блоки тегов внутри файла xml программным способом, используя xmlstarlet или любые другие библиотеки / инструменты сценариев оболочки ... 1001 *

Комментирование ...

Входной файл:

<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

Выходной файл:

<note>
<to>Tove</to>
<!-- <from>Jani</from> -->
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

Без комментариев ...

Входной файл:

<note>
<to>Tove</to>
<!-- <from>Jani</from> -->
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

Выходной файл:

<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

Ответы [ 2 ]

0 голосов
/ 11 июня 2018

После игры с xlstproc я придумаю решение для некомментированного случая.Функция «содержит» делает трюк ...

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <!--Identity template,
   provides default behavior that copies all content into the output -->
   <xsl:template match="@*|node()">
       <xsl:copy>
           <xsl:apply-templates select="@*|node()"/>
       </xsl:copy>
   </xsl:template>
   <!--More specific template for "from" that provides custom behavior -->
   <xsl:template match="comment()">

       <xsl:if test='contains(.,"&lt;from&gt;")' >
           <xsl:value-of  select="." disable-output-escaping="yes" />
       </xsl:if>

       <xsl:if test='not (contains(.,"&lt;from&gt;"))' > 
           <xsl:copy-of select="." />
       </xsl:if>

   </xsl:template>
</xsl:stylesheet>
0 голосов
/ 06 июня 2018

можно сделать с помощью xsltproc

xsltproc  comment-from.xslt  input.xml

comment-from.xslt

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <!--Identity template,
    provides default behavior that copies all content into the output -->
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>
  <!--More specific template for "from" that provides custom behavior -->
  <xsl:template match="from">
    <xsl:comment>
      <xsl:text><![CDATA[ <from>]]></xsl:text>
      <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
      </xsl:copy>
      <xsl:text><![CDATA[</from> ]]></xsl:text>
    </xsl:comment>
  </xsl:template>
</xsl:stylesheet>
...