Java的XML解析器似乎認爲我的XML文檔沒有很好地在根元素之後形成。但我用幾種工具驗證了它們,但它們都不同意。這可能是我的代碼中的錯誤,而不是文檔本身。我非常感謝你們可以爲我提供的任何幫助。Java說XML文檔沒有很好形成
這裏是我的Java方法:
private void loadFromXMLFile(File f) throws ParserConfigurationException, IOException, SAXException {
File file = f;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db;
Document doc = null;
db = dbf.newDocumentBuilder();
doc = db.parse(file);
doc.getDocumentElement().normalize();
String desc = "";
String due = "";
String comment = "";
NodeList tasksList = doc.getElementsByTagName("task");
for (int i = 0; i tasksList.getLength(); i++) {
NodeList attributes = tasksList.item(i).getChildNodes();
for (int j = 0; i < attributes.getLength(); j++) {
Node attribute = attributes.item(i);
if (attribute.getNodeName() == "description") {
desc = attribute.getTextContent();
}
if (attribute.getNodeName() == "due") {
due = attribute.getTextContent();
}
if (attribute.getNodeName() == "comment") {
comment = attribute.getTextContent();
}
tasks.add(new Task(desc, due, comment));
}
desc = "";
due = "";
comment = "";
}
}
以下是我試圖加載XML文件:
<?xml version="1.0"?>
<tasklist>
<task>
<description>Task 1</description>
<due>Due date 1</due>
<comment>Comment 1</comment>
<completed>false</completed>
</task>
<task>
<description>Task 2</description>
<due>Due date 2</due>
<comment>Comment 2</comment>
<completed>false</completed>
</task>
<task>
<description>Task 3</description>
<due>Due date 3</due>
<comment>Comment 3</comment>
<completed>true</completed>
</task>
</tasklist>
,這裏是錯誤消息Java是扔我:
run:
[Fatal Error] tasks.xml:28:3: The markup in the document following the root element must be well-formed.
May 17, 2010 6:07:02 PM todolist.TodoListGUI <init>
SEVERE: null
org.xml.sax.SAXParseException: The markup in the document following the root element must be well-formed.
at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:239)
at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:283)
at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:208)
at todolist.TodoListGUI.loadFromXMLFile(TodoListGUI.java:199)
at todolist.TodoListGUI.<init>(TodoListGUI.java:42)
at todolist.Main.main(Main.java:25)
BUILD SUCCESSFUL (total time: 19 seconds)
作爲參考TodoListGUI.java:199是
doc = db.parse(file);
如果背景是有幫助的人在這裏,我想編寫一個簡單的GUI應用程序來管理,可以讀取和寫入和定義任務XML文件的待辦事項列表。
你可以發佈一個示例XML文檔嗎? – 2010-05-17 22:13:16
您的XML標籤似乎已被吃掉 - 您可以編輯它們以使其可見嗎?你應該可以通過''<''得到'<'。 – psmears 2010-05-17 22:14:24
@psmears:no,只需縮進4個空格或選擇代碼,然後按下編輯器工具欄中的「010101」按鈕或「Ctrl + K」鍵。 – BalusC 2010-05-18 00:18:57