XML Only one root Element allowed

狂风中的少年 提交于 2020-02-08 10:45:06

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!