【发布时间】:2017-04-27 14:44:00
【问题描述】:
我正在处理一个 xml 文件,我必须将其值写入 csv 文件作为输出,我能够读取 xml 文件,但我无法使用该值生成 csv 文件,我给出了xml和java代码我到目前为止所做的,
<?xml version="1.0" ?>
<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>
<Zip>66612</Zip>
<City>Topeka</City>
</ThirdParty>
这是我的 xml 文件,我可以在控制台上打印其值,我需要将其写入 csv 文件,其中每个标签都将是标题,值将是标签内的值。
public class Main {
public static void main(String[] args) throws XPathExpressionException, SAXException, IOException, ParserConfigurationException {
Writer writer = new OutputStreamWriter(new FileOutputStream("src/main/resources/pathToFile"), "UTF-8");
BufferedWriter bw = new BufferedWriter(writer);
DocumentBuilderFactory domFactory =
DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse("src/main/resources/new.xml");
XPath xpath = XPathFactory.newInstance().newXPath();
// XPath Query for showing all nodes value
XPathExpression expr = xpath.compile("pagedata/ThirdParty/*/text()");
String pyTemporaryObject = null ,line = null;
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(nodes.item(i).getNodeValue()); // this line prints the output.
// this piece of code I have tried to write into a csv which did not worked
Node node = nodes.item(i);
Element element = (Element) node;
pyTemporaryObject = element.getElementsByTagName("pyTemporaryObject").item(0).getTextContent();
line = String.format("%s", pyTemporaryObject);
System.out.println(pyTemporaryObject);
bw.write(line);
bw.newLine();
bw.flush();Node node = nodes.item(i);
Element element = (Element) node;
pyTemporaryObject = element.getElementsByTagName("pyTemporaryObject").item(0).getTextContent();
line = String.format("%s", pyTemporaryObject);
System.out.println(pyTemporaryObject);
bw.write(line);
bw.newLine();
bw.flush();
}
}
}
请帮我生成结构为的csv文件
Name | Phone | State | Address1 | pxObjClass | Zip | City
Karen Wallace | 785-296-7829 | KS | 420 SW 9th Street | PCore-Compliance-Commsys-Data-ThirdParty | 66612 | Topeka
每个标签将是标题列,值将在其下方。
【问题讨论】:
-
几个问题:
pyTemporaryObject在你的 xml 中在哪里?为什么你有重复的代码(见最后)?您需要关闭BufferedWriter,并且所有代码都应该在try..catch中,请发布正确的输入。