我有一个大的xml文件,其中包含许多自闭标签.如何使用XSLT删除所有这些.
例如.
<?xml version="1.0" encoding="utf-8" ?>
<Persons>
<Person>
<Name>user1</Name>
<Tel />
<Mobile>123</Mobile>
</Person>
<Person>
<Name>user2</Name>
<Tel>456</Tel>
<Mobile />
</Person>
<Person>
<Name />
<Tel>123</Tel>
<Mobile />
</Person>
<Person>
<Name>user4</Name>
<Tel />
<Mobile />
</Person>
</Persons>
Run Code Online (Sandbox Code Playgroud)
我期待结果:
<?xml version="1.0" encoding="utf-8" ?>
<Persons>
<Person>
<Name>user1</Name>
<Mobile>123</Mobile>
</Person>
<Person>
<Name>user2</Name>
<Tel>456</Tel>
</Person>
<Person>
<Tel>123</Tel>
</Person>
<Person>
<Name>user4</Name>
</Person>
</Persons>
Run Code Online (Sandbox Code Playgroud)
注意:有数千种不同的元素,如何以编程方式删除所有自闭标签.另一个问题是如何删除空元素等<name></name> .
谁可以帮我这个事?非常感谢.
自闭标签相当于空标签.您可以删除所有空标记,但无法知道它们是否在输入XML中是自关闭的(<tag/>并且<tag></tag>无法区分).
<!-- the identity template copies everything that has no special handler -->
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*" />
</xsl:copy>
</xsl:template>
<!-- special handler for elements that have no child nodes:
they are removed by this empty template -->
<xsl:template match="*[not(node())]" />
Run Code Online (Sandbox Code Playgroud)
如果您的定义中仅包含空格的元素也是"空",则将第二个模板替换为:
<xsl:template match="*[normalize-space() = '']" />
Run Code Online (Sandbox Code Playgroud)