有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java XML解析时,标记必须是格式良好的

我的XML文件的格式如下:

<top>
  <name></name>
  <title></title>
  <time></time>
</top>
<top>
  ...
</top>
<top>
  ...
</top>

我编写以下代码来读取xml文件:

DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new File(QUERY_FILE));  //LINE (*)
doc.getDocumentElement().normalize();

NodeList nList = doc.getElementsByTagName("top");

但问题是我在第(*)行得到了错误:

The markup in the document following the root element must be well-formed.

这个错误似乎是因为xml文件中有多个根元素。一种解决方案是在所有<top>元素之外添加<doc></doc>。但是,有没有其他方法可以直接读取像元素数组这样的XML文件


共 (2) 个答案

  1. # 1 楼答案

    您需要为格式良好的应用程序添加以下行:

    <?xml version="1.0" encoding="UTF-8"?> <!  this line >
    <top>
      <name></name>
      <title></title>
      <time></time>
    </top>
    

    使用此页面查看您的文档是否正确,因为它为该元语言设定了标准。 http://validator.w3.org/#validate_by_input

    验证xml dtd等

    万维网联盟(W3C)是万维网(简称WWW或W3)的主要国际标准组织字体维基百科

  2. # 2 楼答案

    您可以尝试隔离每个<top>元素,并尝试分别解析它们,但这是一个比仅围绕xml内容包装<doc></doc>更麻烦的解决方案

    我过去做过的一件事是,我没有将根标记放在文件本身中,而是将文本读入字符串,并在加载XML之前将<doc></doc>标记环绕字符串