2

I've got this XML file:

<persons>
  <person>
    <fname>Tim</fname>
    <lname>DiRusso</lname>
    <languages>Java,PHP</languages>
    <days>Monday,Tuesday</days>
    <frameworks>NodeJS,Django</frameworks>
  </person>
</persons>

I'm trying to add a new 'person' node to go inside the persons block like this:

InputStream is = sc.getResourceAsStream(_filename);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbFactory.newDocumentBuilder();
org.w3c.dom.Document document = db.parse(is);

Element root = document.getDocumentElement();
Element personNode =  (Element) root.getElementsByTagName("person").item(0);
Element newPerson = document.createElement("person");

Element firstName = document.createElement("fname");
firstName.setTextContent("AppendedNode");
newPerson.appendChild(firstName);

personNode.appendChild(newPerson);

DOMSource source = new DOMSource(document);

TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
StreamResult result = new StreamResult(res.getWriter());
transformer.transform(source, result);

And Chrome is giving the error (this happens on the transform line):

error on line 11 at column 11: Extra content at the end of the document

I can't figure out why or how extra content would be at the end of the document?

timdirusso
  • 51
  • 1
  • 8
  • 1
    *Chrome is giving the error* how/where are you executing the code ? – Ravi Jan 21 '18 at 07:18
  • @Ravi Deployed on a Tomcat server within Eclipse. – timdirusso Jan 21 '18 at 07:20
  • 1
    `Element personNode = (Element) root.getElementsByTagName("person").item(0);` why ? – Ravi Jan 21 '18 at 07:30
  • @Ravi To append the new node after that existing node. I've also tried to append the new node to root and get the same error. I feel like I'm appending to the wrong place but there isn't anywhere else to try – timdirusso Jan 21 '18 at 07:33
  • @Ravi Just fixed. I had a line `out.println("Form");` that was throwing off the tags in the browser – timdirusso Jan 21 '18 at 07:39

0 Answers0