有条件地删除 XML 文件的一部分 [英] Condtionally remove section of XML file

查看:29
本文介绍了有条件地删除 XML 文件的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找这个问题的解决方案,并且怀疑 awk 应该提供一个足够简单的解决方案,而不是我笨拙的 shell 脚本.

I am looking for a solution to this problem and suspect awk should provide a simple enough solution instead of my clumsy shell script.

我有一个由多个部分组成的 xml 文件,如下所示.我还有一个值列表.

I have an xml file consisting of multiple sections as shown below. I also have a list of values.

对于每个部分 ... </top_tag> 其中 value_x 在我的列表中,删除(即:不打印)部分 <top_tag>... </top_tag>

For each section <top_tag> ... </top_tag> where value_x is in my list, delete (ie:not print) the section <top_tag> ... </top_tag>

<xml>
<outer_tag>
   <top_tag>
      <tag>value_1</tag>
      <other_tags></other_tags>
   </top_tag>
   <top_tag>
      <tag>value_2</tag>
      <other_tags></other_tags>
   </top_tag>
    ...
   <top_tag>
      <tag>value_n</tag>
      <other_tags></other_tags>
   </top_tag>
</outer_tag>

非常感谢您的建议.

推荐答案

这里您需要的不是 awk,而是 XSLT,它是专门为此类任务创建的.它允许您将 xml 文档转换为不同的 xml.

What you need here is not awk but XSLT, which was created specifically for this kind of tasks. It lets you transform an xml document into a different xml.

对于与您非常相似的输入:

For an input much like yours:

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="example.xsl"?>
<outer_tag>
   <top_tag>
      <tag>value_1</tag>
      <other_tags></other_tags>
   </top_tag>
   <top_tag>
      <tag>value_2</tag>
      <other_tags></other_tags>
   </top_tag>
   <top_tag>
      <tag>value_3</tag>
      <other_tags></other_tags>
   </top_tag>
   <top_tag>
      <tag>value_n</tag>
      <other_tags></other_tags>
   </top_tag>
</outer_tag>

以下 XSLT 删除了所有带有 value_3top_tag 元素,方法是简单地不复制它们并忽略它们的内容.

The following XSLT removes all top_tag elements with value_3 by simply not copying them and ignoring their contents.

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="*">
        <xsl:element name="{name()}">           
            <xsl:apply-templates select="child::node()"></xsl:apply-templates>
        </xsl:element>
    </xsl:template>

    <xsl:template match="top_tag[tag = 'value_3']">     
    </xsl:template>
</xsl:stylesheet

每种主要的编程语言都至少有几个可以根据 XSLT 处理 XML 输入的库.命令行工具和基于 UI 的应用程序(IDE,但不仅仅是那些)也可以做到这一点.最后,如果您将 xsl 文件包含在这样的处理指令中,Web 浏览器可以使用 XSLT 转换文件:

Every major programming language has at least a couple of libraries that can process an XML input according to an XSLT. Command line tools and UI-based applications (IDEs but not only those) can do it as well. Finally, web browsers can transform files using XSLT if you include the xsl file with a processing instruction like this:

<?xml-stylesheet type="text/xsl" href="example.xsl"?>

这篇关于有条件地删除 XML 文件的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆