需要读取看起来像XML的文本文件。文本文件包含多个XML文件,带有父标记。需要逐行解析文件并需要编写所需子标记的相应元素甚至在父标签中多次重复,在一行中,到另一个文本文件。需要将元素写入父标签后的下一行。我知道如何读取文件并写入文件,但我无法得到逻辑,根据要求阅读它。请帮助我。非常感谢任何帮助。
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>
答案 0 :(得分:1)
手工解析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());
答案 1 :(得分:0)
您必须使用队列结构[先进先出]
你的基本算法就像
当然,您可以使用其他库。