简体   繁体   English

在没有父节点的情况下解析XML文档-JAVA

[英]Parse XML document without a parent node - JAVA

I have an XML file that needs to be parsed to output the data of an element. 我有一个XML文件,需要对其进行分析以输出元素的数据。 However, the file doesn't have a parent node and the conventional way to parse XML files is giving me this error: 但是,该文件没有父节点,并且解析XML文件的常规方法给了我这个错误:

The markup in the document following the root element must be well-formed. 根元素后面的文档中的标记必须格式正确。

XML File: XML档案:

<row>
    <dam>bellair dam</dam>
    <last_year>70.6</last_year>
    <fsc>4.3</fsc>
    <latitude>33:42:43</latitude>
    <river>brak river</river>
    <last_week>35.9</last_week>
    <this_week>35.9</this_week>
    <longitude>20:35:52</longitude>
</row>
<row>
    <dam>berg river dam</dam>
    <last_year>52.7</last_year>
    <fsc>127.1</fsc>
    <latitude>33:54:25</latitude>
    <river>berg river</river>
    <last_week>37.3</last_week>
    <this_week>38.2</this_week>
    <longitude>19:3:30</longitude>
</row>
<row>
    <dam>brandvlei dam</dam>
    <last_year>38.0</last_year>
    <fsc>286.1</fsc>
    <latitude>33:42:42.88</latitude>
    <river>lower brandvlei river</river>
    <last_week>20.7</last_week>
    <this_week>20.5</this_week>
    <longitude>19:25:7.85</longitude>
</row>

Is there a way to parse the data in the XML file as string and use string manipulation to work on it? 有没有一种方法可以将XML文件中的数据解析为字符串并使用字符串操作对其进行处理? Because the conventional way of parsing the file is not working. 因为解析文件的常规方法不起作用。 Plus I cannot change (add) a root node to the XML file. 另外,我无法将根节点更改(添加)到XML文件。 Or how about writing the data to a text file? 或将数据写入文本文件怎么样?

Example of output: 输出示例:

Enter name of the data file:
testdata.xml
The dams are:
bellair dam
berg river dam
brandvlei dam

Because you have a malformed XML you will have a few options. 因为您的XML格式不正确,所以您将有一些选择。 You can either modify the input, write your own parser or partially parse each row as an xml. 您可以修改输入,编写自己的解析器或将每行部分解析为xml。

A suggestion: 一条建议:

File file = new File("malformedXmlMissingRoot.xml");
FileInputStream fis = new FileInputStream(file);
List<InputStream> streams = Arrays.asList(
    new ByteArrayInputStream("<root>".getBytes()),
    fis,
    new ByteArrayInputStream("</root>".getBytes()));
InputStream cntr = new SequenceInputStream(Collections.enumeration(str));

and use that InputStream in your typical XML parser. 并使用InputStream在典型的XML解析器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM