gpt4 book ai didi

java - 如何定义正确的 XSLT?

转载 作者:行者123 更新时间:2023-11-29 05:43:50 24 4
gpt4 key购买 nike

假设我有以下 XML,我只关心 FruitId、客户 Numbereaten 和 Weight 属性。

<AllFruits xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<!-- All fruits below. -->
<Fruit>
<FruitId>Bannana</FruitId>
<FruitColor>Yellow</FruitColor>
<FruitShape>Moon</FruitShape>
<Customer>
<Name>Joe</Name>
<Numbereaten>5</NumberEaten>
<Weight>2.6</Weight>
</Customer>
<Customer>
<Name>Mark</Name>
<Numbereaten>8</NumberEaten>
<Weight>5.0</Weight>
</Customer>
</Fruit>
<Fruit>
<FruitId>Apple</FruitId>
<FruitColor>Red</FruitColor>
<FruitShape>Circle</FruitShape>
<Customer>
<Name>Joe</Name>
<Numbereaten>2</NumberEaten>
<Weight>1.5</Weight>
</Customer>
</Fruit>
<Fruit>
<FruitId>Pear</FruitId>
<FruitColor>Green</FruitColor>
<FruitShape>Oval</FruitShape>
<Customer>
<Name>Mark</Name>
<NumberEaten>1</NumberEaten>
<Weight>6</Weight>
</Customer>
<Customer>
<Name>Josh</Name>
<NumberEaten>9</NumberEaten>
<Weight>10</Weight>
</Customer>
<Customer>
<Name>Willis</Name>
<NumberEaten>2</NumberEaten>
<Weight>5.6</Weight>
</Customer>
</Fruit>
</AllFruits>

上述内容的正确 XSLT 是什么?我尝试了以下方法,但没有用。

<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:output method="text" encoding="ISO-8859-1" />
<xsl:variable name="newline" select="'&#xA;'"/>
<xsl:template match="Fruit">
<xsl:for-each select="Customer">
<xsl:value-of select="preceding-sibling::FruitId" />
<xsl:text>,</xsl:text>
<xsl:value-of select="Numbereaten" />
<xsl:text>,</xsl:text>
<xsl:value-of select="Weight" />
<xsl:value-of select="$newline" />
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>

为了尝试测试 XSLT,我使用了以下 Java 代码:

   Source xmlSource = new StreamSource(new File("xmlFile"));
Source xsltSource = new StreamSource(new File("xsltFile"));
Transformer transformer = TransformerFactory.newInstance().newTransformer(xsltSource);
transformer.transform(xmlSource, new StreamResult(System.out));

我得到的只是将 XML 输出到控制台...不是我想要的格式:

Bannana, 5, 2.6
Bannana, 8, 5
...
Apple 6, 5
Apple 3, 2

如果我尝试做的事情不起作用,如果有 XSLT 以外的其他更好的方法,请告诉我。感觉像这样的事情应该很简单。

最佳答案

如果您想去掉空行,只需在 XSLT 文件的行后添加即可

<xsl:variable name="newline" select="'&#xA;'"/> 

这一行

<xsl:strip-space elements="*" />

关于java - 如何定义正确的 XSLT?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16504212/

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