需要读取一个文本文件,它看起来像一个由多个XML文件组成的XML.The文本文件,带有一个父标签.Need来解析文件,并逐行解析文件,需要将所需的子标签的相应元素写到另一个文本文件.Need中,甚至在父标签内重复多次,在一行中将元素写到父标签之后的下一行。我知道如何读取文件和写入文件,但我无法按照要求获得读取它的逻辑.Please帮助我走出.Any帮助非常感谢。
1234566546 AbcdeXYZ-23243423 1030253498 23423423423 <parentnode xmlns="http://www.fpml.org/FpML-5/recordkeeping" fpmlVersion="5-5" xmlns:abcde="http://www.abcde.com/ext" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.abcde.com/ext /../xmls/XYZ/recordkeeping/abcde-ext.xsd">
<Child1 Child1Scheme="http://www.google.com">1234566546</Child1>
<Child1 Child1Scheme="http://www.fpml.org/coding-scheme/external/UNique">AbcdeXYZ-154555</Child1>
<country countryScheme="http://www.fpml.org/coding-scheme/external/country-identifier">1030253498</country>
<state stateScheme="http://www.fpml.org/coding-scheme/external/state-identifier">434343242</state>
</parentnode>
<parentnode xmlns="http://www.fpml.org/FpML-5/recordkeeping" fpmlVersion="5-5" xmlns:abcde="http://www.abcde.com/ext" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.abcde.com/ext /../xmls/XYZ/recordkeeping/abcde-ext.xsd">
<Child1 Child1Scheme="http://www.google.com">1234566546</Child1>
<Child1 Child1Scheme="http://www.fpml.org/coding-scheme/external/UNique">AbcdeXYZ-4566545</Child1>
<country countryScheme="http://www.fpml.org/coding-scheme/external/country-identifier">1030253498</country>
<state stateScheme="http://www.fpml.org/coding-scheme/external/state-identifier">2323232323</state>
</parentnode>发布于 2014-03-28 04:28:29
手工解析xml是一种痛苦的时间浪费。如果只创建一个带有包装标签的临时文件并使用xml解析器,会容易得多,如下所示:
Path inputFile = Paths.get("input.xml");
Path tempFile = Paths.get("temp.xml");
Path outputFile = Paths.get("output.xml");
// make a temp file with fixed xml formatting
Files.write(tempFile, "<root>".getBytes());
for (String line : Files.readAllLines(inputFile, StandardCharsets.UTF_8)) {
Files.write(tempFile, line.getBytes(), StandardOpenOption.APPEND);
}
Files.write(tempFile, "</root>".getBytes(), StandardOpenOption.APPEND);
// parse xml and build output string
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(tempFile.toFile());
StringBuilder sb = new StringBuilder();
NodeList parents = doc.getElementsByTagName("parentnode");
for (int i = 0; i < parents.getLength(); i++) {
NodeList children = parents.item(i).getChildNodes();
for (int j=0; j<children.getLength(); j++) {
sb.append(children.item(j).getTextContent() + " ");
}
}
// clean up temp file
Files.delete(tempFile);
// write output file
Files.write(outputFile, sb.toString().getBytes());发布于 2014-03-28 03:27:06
您必须使用先进先出的队列结构
你的基本算法是这样的
当然,您还可以使用其他库。
https://stackoverflow.com/questions/22697118
复制相似问题