在 Java 中打印 XML 标记名称和值 [英] Print XML tag names and values in Java
本文介绍了在 Java 中打印 XML 标记名称和值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 XML 文档,我想打印文档中所有标签的标签名称和值(叶节点).
例如,对于 XML:
<书架><书><name>Book1</name><价格>$10</价格>书><书><name>Book2</name><价格>$15</价格>书></书架></图书馆>
输出应该是这样的:
图书馆=书架=书=名称=Book1价格=$10书=名称=Book2价格=$15
请帮忙!
解决方案
Minimalistic XSLT 1.0 方法:
给出:
<前>图书馆=书架=书=名称=Book1价格=$10书=名称=Book2价格=$15这个替代模板会更好地处理节点值:
<xsl:value-of select="name()"/><xsl:text>=</xsl:text><xsl:if test="normalize-space(text()) != ''"><xsl:value-of select="text()"/></xsl:if><xsl:text> </xsl:text><xsl:apply-templates/></xsl:模板>
输出与之前相同,但会保留节点值内的间距.
I have an XML document, and I want to print the tag names and values (of leaf nodes) of all tags in the document.
For example, for the XML:
<library>
<bookrack>
<book>
<name>Book1</name>
<price>$10</price>
</book>
<book>
<name>Book2</name>
<price>$15</price>
</book>
</bookrack>
</library>
The output should be something like:
library=
bookrack=
book=
name=Book1
price=$10
book=
name=Book2
price=$15
Help please!
解决方案
Minimalistic XSLT 1.0 approach:
<xsl:stylesheet
version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
>
<xsl:output method="text" />
<xsl:template match="*">
<xsl:value-of select="name()" />
<xsl:text>=</xsl:text>
<xsl:value-of select="normalize-space(text())" />
<xsl:text> </xsl:text>
<xsl:apply-templates />
</xsl:template>
<xsl:template match="text()" />
</xsl:stylesheet>
gives:
library= bookrack= book= name=Book1 price=$10 book= name=Book2 price=$15
This alternative template would treat the node values better:
<xsl:template match="*">
<xsl:value-of select="name()" />
<xsl:text>=</xsl:text>
<xsl:if test="normalize-space(text()) != ''">
<xsl:value-of select="text()" />
</xsl:if>
<xsl:text> </xsl:text>
<xsl:apply-templates />
</xsl:template>
The output is the same as before, but spacing within node values would be retained.
这篇关于在 Java 中打印 XML 标记名称和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文