转换文档的最快方法是什么:
<customermodel:Customer>
<creditCards>
<cardNumber>@0</cardNumber>
<provider>@HSBC</provider>
<xsi:type>@customermodel:CreditCard</xsi:type>
23242552
</creditCards>
.
.
这样带有@的元素就成为父元素的属性。
即到达:
<customermodel:Customer>
<creditCards cardNumber="0" provider="HSBC" xsi-type="customermodel:CreditCard>
232323232
</creditCards>
.
.
使用 dom?或 Sax 解析器或手动?我可以将 @ 移至 <> 的
最佳答案
如果您决定使用 XSLT,它将看起来像这样
<!-- process element and attributes first so that whitespace doesn't interfere -->
<xsl:template match="creditCards">
<xsl:copy>
<xsl:apply-templates select="* | @*"/>
<xsl:apply-templates select="text()"/>
</xsl:copy>
</xsl:template>
<!-- change childrent of creditCards to attributes and strip first charcter from value -->
<xsl:template match="creditCards/*">
<xsl:attribute name="{name()}">
<xsl:value-of select="substring(., 2)"/>
</xsl:attribute>
</xsl:template>
<!-- rename xsi:type -->
<xsl:template match="creditCards/xsi:type">
<xsl:attribute name="xsi-type">
<xsl:value-of select="substring(., 2)"/>
</xsl:attribute>
</xsl:template>
<!-- identity transform -->
<xsl:template match="node() | @*">
<xsl:copy>
<xsl:apply-templates select="node() | @*"/>
</xsl:copy>
</xsl:template>
关于Java XML 解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/714056/