java如何在使用documentBuilderFactory解析时管理xml中的嵌套循环
我正在解析一个具有嵌套标记的xml文件,我正在使用xsl将模式与xml匹配,我的任务是选择所有标记值并将其写入csv文件。我能够读取和写入xml和csv文件,但是,当涉及到嵌套循环时,csv文件中的数据没有正确传输,我给出了我的代码和我所做的
我的xml文件
<?xml version="1.0" ?>
<pagedata>
<pyTemporaryObject>false</pyTemporaryObject>
<ResolutionCode>Policy Adjustment Action</ResolutionCode>
<Origin>DOI</Origin>
<InsuredFName>Buffy</InsuredFName>
<ThirdParty>
<Name>Karen Wallace</Name>
<Phone>785-296-7829</Phone>
<State>KS</State>
<Address1>420 SW 9th Street</Address1>
<pxObjClass>PCore-Compliance-Commsys-Data-ThirdParty</pxObjClass>
</ThirdParty>
</pagedata>
我的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="/">
pyTemporaryObject,ResolutionCode,Origin,InsuredFName,Name,Phone,State,Address1,pxObjClass
<xsl:for-each select="//pagedata">
<xsl:value-of select="concat (pyTemporaryObject,',',ResolutionCode,',',Origin,',',InsuredFName,'
')"/>
<xsl:for-each select="//ThirdParty">
<xsl:value-of select="concat (Name,',',Phone,',',State,',',Address1,',',pxObjClass,'
')"/>
</xsl:for-each>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
还有我的Java类
public class Xml2Csv {
public static void main(String args[]) throws Exception{
File stylesheet = new File("src/main/resources/newStyle.xsl");
File xmlSource = new File("src/main/resources/parse.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("src/main/resources/y.csv"));
transformer.transform(source, outputTarget);
}
}
csv即将发布
pyTemporaryObject|ResolutionCode|Origin|InsuredFName|Name|Phone|State|Address1|pxObjClass
False Policy DOI BUffy // these are the value of the first loop
john 98766 west ../// these are the values of the second loop
但我需要这两个值到同一行。。。请帮忙,谢谢
# 1 楼答案
我认为您真正需要做的就是将外部
xsl:for-each
中的xsl:value-of
移到内部,然后更改xpath引用以相应地选择父值请注意,如果可能没有
ThirdParty
元素,但仍然需要行输出,请尝试此方法