【发布时间】:2015-09-03 02:46:13
【问题描述】:
我已经通过了这个解决方案,但它涵盖了单级嵌套,我的要求是通过多级嵌套并将值放在同一行中
Convert an XML file to CSV file using java
我下面有这种xml的输入格式。
<?xml version="1.0"?>
<CstmrCdtTrfInitn>
<GrpHdr>
<MsgId>ABC/123</MsgId>
<NbOfTxs>1000</NbOfTxs>
<InitgPty>
<Nm>ABC</Nm>
</InitgPty>
<PmtInf>
<DbtrAcct>
<Id>
<Othr>
<Id>00000007010</Id>
</Othr>
</Id>
</DbtrAcct>
</PmtInf>
</GrpHdr>
</CstmrCdtTrfInitn>
下面我的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,NbOfTxs,Nm,ID
<xsl:for-each select="//CstmrCdtTrfInitn">
<xsl:value-of select="concat(MsgId,NbOfTxs,',',Nm,',',ID,'
')"/>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
我在另一行获取 nm 和 ID,
下面是我的代码
class Xml2Csv {
public static void main(String args[]) throws Exception {
File stylesheet = new File("src/main/resources/style.xsl");
File xmlSource = new File("src/main/resources/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("/tmp/x.csv"));
transformer.transform(source, outputTarget);
}
}
我需要如下 CSV 格式的输出
MsgId,NbOfTxs,Nm(Inside the InitgPty tag ),ID((Inside the other tag )) as the header
ABC/123,1000,ABC,00000007010 as values
单行
【问题讨论】:
-
糟糕,缩进 XML 表明您缺少
</PmtInf>标记。当! XML 解析错误。 -
所以你问如何写一个
XSLT样式表来做到这一点?从隐藏在您提供的链接上某处的样式表开始。请更新问题以包含所有相关信息,并显示您到目前为止所做的尝试。 --- 如果您不知道如何编写XSLT样式表,我建议您开始阅读它。 -
你能不能试试看你得到了什么。请把你的话拼写完整。 --- 你了解 XSLT 吗?是做什么的?这个怎么运作?你读过关于 XSLT 的任何东西吗?如果没有,也许可以尝试非 XSLT 解决方案。