gpt4 book ai didi

java - Java 中类似于 XML 的文本文件解析

转载 作者:行者123 更新时间:2023-12-01 13:13:00 24 4
gpt4 key购买 nike

需要读取一个类似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>

最佳答案

手动解析 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());

关于java - Java 中类似于 XML 的文本文件解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22697118/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com