gpt4 book ai didi

java - 使用 Java 或 XSLT 从 XML 中删除一组指定的空标签

转载 作者:行者123 更新时间:2023-12-01 09:26:33 27 4
gpt4 key购买 nike

我需要从 XML 中删除一组指定的标签(如果它们为空)。

例如:

<xml><tag1>value<tag1><tag2></tag2><tag3>value<tag3><tag4/><tag5/><xml>

在此,要删除的标签(如果它们为空)是:

tag2, tag4

预期结果:

<xml><tag1>value<tag1><tag3>value<tag3><tag5/><xml>

使用纯 Java 或 XSLT 实现此目的的最佳方法是什么?除此之外,我们是否有可以用于相同用途的第三方库?

问候,阿努普

最佳答案

tags from an XML if they are empty.

什么是空?“空”有不同的可能定义:

  1. 没有 child
  2. 没有文字
  3. 没有空白文本节点(例如“”、CR、NL、#x20, #x9, #xD or #xA.)
  4. 上述组合

测试研究输入:

<root>
<tag1>value</tag1>
<tag2></tag2>
<tag3><tag3_1/></tag3>
<tag4><tag4_1/> </tag4>
<tag5> </tag5>
<tag6/>
<tag7>

</tag7>
</root>

测试学习转换:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>

<xsl:template match="root">

<!-- no childs (element nodes) -->
<xsl:text>"*[not(*)]" matches: </xsl:text>
<xsl:for-each select="*[not(*)]">
<xsl:value-of select="name()"/><xsl:text> </xsl:text>
</xsl:for-each>
<xsl:text>&#10;</xsl:text>

<!-- see function node() in thread -->
<xsl:text>"*[not(node())]" matches: </xsl:text>
<xsl:for-each select="*[not(node())]">
<xsl:value-of select="name()"/><xsl:text> </xsl:text>
</xsl:for-each>
<xsl:text>&#10;</xsl:text>

<!-- no textnodes -->
<xsl:text>"*[not(text())]" matches: </xsl:text>
<xsl:for-each select="*[not(text())]">
<xsl:value-of select="name()"/><xsl:text> </xsl:text>
</xsl:for-each>
<xsl:text>&#10;</xsl:text>

<!-- no textnodes reduced by whitespaces -->
<xsl:text>"*[not(normalize-space(.))]" matches: </xsl:text>
<xsl:for-each select="*[not(normalize-space(.))]">
<xsl:value-of select="name()"/><xsl:text> </xsl:text>
</xsl:for-each>
<xsl:text>&#10;</xsl:text>

<!-- combination -->
<xsl:text>"*[not(normalize-space(.)) and not(*)]" matches: </xsl:text>
<xsl:for-each select="*[not(normalize-space(.)) and not(*)]">
<xsl:value-of select="name()"/><xsl:text> </xsl:text>
</xsl:for-each>
<xsl:text>&#10;</xsl:text>

</xsl:template>
</xsl:stylesheet>

输出:

"*[not(*)]" matches: tag1 tag2 tag5 tag6 tag7 
"*[not(node())]" matches: tag2 tag6
"*[not(text())]" matches: tag2 tag3 tag6
"*[not(normalize-space(.))]" matches: tag2 tag3 tag4 tag5 tag6 tag7
"*[not(normalize-space(.)) and not(*)]" matches: tag2 tag5 tag6 tag7
<小时/>

函数 node() 匹配可以通过 child::axis: 选择的任何节点类型:

  • 元素
  • 文本节点
  • 处理指令 (PI) 节点
  • 评论节点。

关于java - 使用 Java 或 XSLT 从 XML 中删除一组指定的空标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39785696/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com