[英]Removing a specified set of empty tags from in XML using Java or XSLT
如果它們為空,我需要從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實現此目標的最佳方法是什么? 除此之外,我們還有一個可以用於同一事物的第三方庫嗎?
問候,阿努普
XML中的廣告代碼(如果為空)。
什么是空的? “空”有不同的可能定義:
測試研究輸入:
<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> </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> </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> </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> </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> </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 ::軸選擇的任何節點類型匹配:
要刪除的標簽(如果為空)為:
tag2, tag4
這在XSLT中很簡單:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>
<!-- identity transform -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="tag2[not(node())] | tag4[not(node())]"/>
</xsl:stylesheet>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.