使用xsl

时间:2016-12-08 08:43:29

标签: java xml csv xslt xml-parsing

我有以下代码将XML传输到CSV,但是输入(在csv中),第一行是空白(空)。

你能告诉我有什么问题吗?

Java类

public class ReadXML {
    public static void main(String[] args) throws TransformerException, SAXException, IOException, ParserConfigurationException {
        File stylesheet = new File("C:\\style.xsl");
        File xmlSource = new File("C:\\data.xml");

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(xmlSource);

        StreamSource stylesource = new StreamSource(stylesheet);
                Transformer transformer = TransformerFactory.newInstance().newTransformer(stylesource);

                Source source = new DOMSource(document);

                Result outputTarget = new StreamResult(new File("C:\\x.csv"));
        transformer.transform(source, outputTarget);
    }
}

XSL样式表:(style.xsl)

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format" >
<xsl:output method="text" omit-xml-declaration="yes" indent="no"/>
<xsl:template match="/">
MsgId,PartnerId,OrderId
<xsl:for-each select="//orderDetails">
<xsl:value-of select="concat(MsgId,',',PartnerId,',',OrderId,'&#xA;')"/>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>

XML数据 :( data.xml)

<?xml version="1.0" encoding="UTF-8"?>
<orders>
    <orderDetails>
        <MsgId>text1</MsgId>
        <PartnerId>text1</PartnerId>
        <OrderId>text1</OrderId>
    </orderDetails>
    <orderDetails>
        <MsgId>text11</MsgId>
        <PartnerId>text11</PartnerId>
        <OrderId>text11</OrderId>
    </orderDetails>
</orders>

1 个答案:

答案 0 :(得分:3)

在元素xsl:text:

中插入标题
cell