问题
I get an Error within this Code while trying to add a new Element.
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(openFileInput(filename));
Node task = doc.getElementsByTagName("task").item(position);
NodeList list = task.getChildNodes();
for(int i = 0; i<list.getLength();i++){
Node node = list.item(i);
if("task_note".equals(node.getNodeName())){
node.setTextContent(taskItems.get(position).get("task_note"));
}
}
Node taskNote = doc.createElement("task_image");
taskNote.setTextContent(taskItems.get(position).get("task_image"));
doc.appendChild(taskNote);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
//DOMSource wandelt Zeichen wie < , > , & , "" automatisch in XML Sprache um
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(openFileOutput(filename,Context.MODE_PRIVATE));
transformer.transform(source,result);
} catch (ParserConfigurationException | IOException | SAXException | TransformerException e) {
e.printStackTrace();
}
Here is the Error:
Caused by: org.w3c.dom.DOMException: Only one root element
at de.appy.laluna.app.TasksList.onActivityResult(TasksList.java:161)
Inside the for loop, I edit the task_note Element. This works until I create a new Element after the for loop.
This leads to the error.
What is wrong and how can I solve the problem?
Kind Regards
回答1:
You can only have 1 root element in an XML document.
It looks like you are loading an existing XML document here:
Document doc = docBuilder.parse(openFileInput(filename));
And getting an existing node from that document here:
Node task = doc.getElementsByTagName("KEVOX_task").item(position);
So, I'm assuming it has a root element already. Since you are getting an element KEVOX_task from that document, it's at least contained within the root element.
Later, you attempt to append to the document itself:
doc.appendChild(taskNote);
This would add more than one root element.
What you probably mean to do was add to your task element that you selected earlier:
task.appendChild(taskNote);
来源:https://stackoverflow.com/questions/31724136/xml-only-one-root-element-allowed