Xml append node problem

Xml append node problem

print("code sample");Question:
I create a XML which looks like this:
              <cwMin>31</cwMin>
         The code used in generating this XML is :
              XMLOutputFactory xof = XMLOutputFactory.newInstance();
              XMLStreamWriter xtw = null;
              StringWriter stringWriter = new        StringWriter();
              xtw = xof.createXMLStreamWriter(stringWriter);
              xtw.writeStartDocument();
              xtw.writeStartElement("cwMin");
              xtw.writeCharacters("31");
              xtw.writeEndElement();
              xtw.writeEndDocument();
              xtw.flush();
              xtw.close();
              System.out.println("111 ---> "+stringWriter.toString());
              Node nds = parse(stringWriter.toString()); //Parse is a custom method to convert String to Node.

Output:

111 --->  <?xml version="1.0" ?><cwMin>31</cwMin>

org.w3c.dom.DOMException: WRONGDOCUMENTERR: A node is used in a different document than the one that created it.

Now that, I already have a node "nd" which is of type org.w3c.dom.Node.
and the value of "nd" is :
<?xml version="1.0" ?>
<wmmApResp>
<wlanId>0</wlanId>
<profileId>2</profileId>
<aifs>6</aifs>
</wmmApResp>

This node "nd" is available in the code above. When I try to append nd to nds using nd.appendChild(nds), I have the following exception: org.w3c.dom.DOMException: WRONGDOCUMENTERR: A node is used in a different document than the one that created it.

How do I rectify/solve this?
View Answers

September 7, 2012 at 3:28 PM

Here is an example that appends a new node to the existing xml document. Here is an xml file where we are going to append a new node.

<?xml version="1.0" encoding="UTF-8" standalone="no"?><school>
<student>
<name>Angelina</name>
<address>Delhi</address>
</student>
<student>
<name>Martina</name>
<address>Mumbai</address>
</student>
</school>

Here is a code that appends a new node student with name and address elements.

import java.io.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;

public class AppendNode {

    public static void main(String[] args) {
        try {
            File xmlFile = new File("C:\\file.xml");
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            Document document = documentBuilder.parse(xmlFile);
            Element documentElement = document.getDocumentElement();
            Element textNode = document.createElement("name");
            textNode.setTextContent("Rose");
            Element textNode1 = document.createElement("address");
            textNode1.setTextContent("Delhi");
            Element nodeElement = document.createElement("student");
            nodeElement.appendChild(textNode);
             nodeElement.appendChild(textNode1);
            documentElement.appendChild(nodeElement);
            document.replaceChild(documentElement, documentElement);
            Transformer tFormer =
                    TransformerFactory.newInstance().newTransformer();
            tFormer.setOutputProperty(OutputKeys.METHOD, "xml");
            Source source = new DOMSource(document);
            Result result = new StreamResult(xmlFile);
            tFormer.transform(source, result);


        } catch (Exception ex) {
            System.out.println(ex);
        }
    }
}









Related Tutorials/Questions & Answers:
Xml append node problem
Xml append node problem   print("code sample");Question: I create... to append a new node. <?xml version="1.0" encoding="UTF-8" standalone="no"?><... to Node. Output: 111 ---> <?xml version="1.0" ?><cwMin>31<
Java append new node to XML file
Java append new node to XML file In this tutorial, you will learn how to append new node to xml file. Sometimes there is a need to append a new XML node to the xml file. Here is an xml file where we are going to append a new node
Advertisements
xml_append - XML
xml_append  hi i have a xml file im.xml its contents: asaddasahellojim i have to add more tags to .. pls help me to solve this.. ...://www.roseindia.net/xml/ Thanks
XML load problem - XML
XML load problem  I have load the xml document in javascript.getting..., Plz give full details with source code to solve the problem and visit to : http://www.roseindia.net/xml/dom/ Thanks    New Document
xml problem - XML
xml problem  URGENT>>>>> how to retrieve data from hash tables without a JDBC connection?????? Thanks & Regards SAIBHARGAV146
java and xml problem - XML
java and xml problem  hi, i need to write a java program that generates an xml file as follows: aaa vvv... XML file: "); //String str = bf.readLine(); int no = Integer.parseInt("1
java program to create xml file with append data in well-formed
java program to create xml file with append data in well-formed   Sorry sir your given xml append data program is not well-formed. I'll make you more clear what I want. If this is my xml file Tom Cruise 45 Now when I append
Problem with external DTD - XML
Problem with external DTD  Hi, This class generate an XML file.But while I am running that generated xml file its giving error as can not locate... classes. OutputFormat of = new OutputFormat("XML","ISO-8859-1",true); of.setIndent
jasper problem - XML
jasper problem  URGENT PROBLEM!!!!!!!!!!!!! how can we use a hash table in jasper reports to generate reports without using database connection directly but access data from the hash table what we needed for creation
Java code to append/add data into a existing xml file
Java code to append/add data into a existing xml file  Java code to append data into a existing xml file, As user enters data it overwrites the previous XML file,I want it to be append the data in XML file rather then overwriting
how to append data to XML file in proper format using JSP
how to append data to XML file in proper format using JSP  hello i was appending my XML file to add more data entered by user in JSP page.But...;/html> XMl file creates successfully at first instance but unable to append
i want to remove specific node in xml file
i want to remove specific node in xml file   <A> <B>hi <C>by <A> <B>hellow <C>how r u ? i want to delet node which is == hellow using java program please help me . tanks in advance
Java--Xml Modify Node Value - Java Beginners
Java--Xml Modify Node Value  I have the following xml. test..., Updating xml node is not sufficient to update that xml. You need to prepare whole xml again after updating the node. Use the following method to update xml
Problem facing in SAX Parsing - XML
Problem facing in SAX Parsing  I have facing the issue in SAX Parsing like i have got the xml and the xml structure is like below... can find the above xml there is no CountryCode in the second record and 4th
Problem facing in SAX Parsing - XML
Problem facing in SAX Parsing  I have facing the issue in SAX Parsing like i have got the xml and the xml structure is like below... 0668420957700159USD you can find the above xml
Java Xml -Node retrieval - Java Beginners
Java Xml -Node retrieval  I have the following xml test_final_1 2009-025T13:23:45 B2B In the above xml,I want to retrieve... = DocumentBuilderFactory.newInstance(); File xmlFile2 = new File("D:\\XML_Utility\\Version 11
java and xml problem. plz see this 1 first - XML
java and xml problem. plz see this 1 first  hi, i need to write a java program that generates an xml file as follows: xxx... in your XML file: "); //String str = bf.readLine(); int no = Integer.parseInt("1
Java-Xml -Modify and Update Node - Java Beginners
Java-Xml -Modify and Update Node   test_final_1 2009-025T13:23...(); System.out.println("XML Data: "); DefaultHandler dHandler = new...){ System.out.println("XML File hasn't any elements"); e.printStackTrace
concat and append
and append?   hiii,ADS_TO_REPLACE_1 Concat is used to add a string at the end of another string.But append() is used with String Buffer to append... string object is created.But in case of StrinBuffer APPEND() that is not the case
DOM Example For Creating a Child Node 
about how to add a Child Node in Dom document. The addition of child node is a very logical. To add a child node first we create blank DOM document and then we create the root node using createElement() method . This root node
append a value to an array
append a value to an array  What?s a way to append a value to an array
problem in creating web application using servelet, jsp, jdbc and xml - JSP-Servlet
problem in creating web application using servelet, jsp, jdbc and xml  Using Servlet, JSP, JDBC and XML create a web application for a courrier...; Hi friend, For solving the problem visit to : http://www.roseindia.net
Append Function in Java
Append Function in Java  What is the use of append function in java? How to use the append function to append a string to a buffer string. Thanks   You can use the StringBuffer class in Java to efficiently append
Read XML in java - XML
Read XML in java  Hi Deepak, I want to read a xml file which have... nikumbh i tried to solve the problem but failed.the program which i hav...; nodeLst.getLength(); s++) { Node fstNode = nodeLst.item(s); Node
MySQL Append
MySQL Append This example illustrates how to append the value of two column. In this example we use the 'CONCAT' function to append the two values of two column.  ADS_TO_REPLACE_1 Query  
uitextfield append text
uitextfield append text  How can i append text or string to UITextField in my iPhone application? Thanks!   Appending a string / text to a UITextField -(Void)buttonPressed { NSString *myS = [NSString stringWithFormat
xml developing - XML
xml developing  I want to develop XML document with following DTD file with XML format. I have also XSL file as a externatl file to represent my xml in browser. my problem is i want to create AUTO unique ID & checksum for each
xml developing - XML
xml developing  I want to develop XML document with following DTD file with XML format. I have also XSL file as a externatl file to represent my xml in browser. my problem is i want to create AUTO unique ID & checksum for each
How to append String in Java?
How to append String in Java?  Hi, I have a number of string in Java which is to be appended efficiently. How to append String in Java? Thanks... efficiently and then get final string. The append() of the class is used
How to Append String In Java?
How to Append String In Java?  How to write program in in Java for appending to a String? How to Append String In Java? What is the best way to do this? Thanks   Hi, The best best to append to a string is to use
Append Arguments to the URL
Append Arguments to the URL  Hi, How to append the query string to the Current Url when i click on a link. AM using Spring MVC i.e. My URL : http://localhost:8080/Sample/SampleApp?id=1 In my page having multiple links (a href
Java get Node Text
of the node in the specified XML file. For this we have create a 'employee.xml' file... Java get Node Text     ... the streams. The class XMLStreamReader reads the entire XML data
MySQL Append
MySQL Append       This example illustrates how to append the values of some columns. We use the 'CONCAT' function to append values of some columns and make
ModuleNotFoundError: No module named 'append-db'
ModuleNotFoundError: No module named 'append-db'  Hi, My Python... 'append-db' How to remove the ModuleNotFoundError: No module named 'append... have to install padas library. You can install append-db python with following
Java get Node Value
Java get Node Value       In this section, you will learn how to obtain the node value. Before any further processing, you need a XML file. For this we have create
can't read my xml file in java
(); } the codes can't read the xml file bcz i want to append the whole xml in my gui...can't read my xml file in java  i've a xml file like this : <...;" + "score: ").append(sd.score).append("<br>
can't read my xml file in java
(); } the codes can't read the xml file bcz i want to append the whole xml in my gui...can't read my xml file in java  i've a xml file like this : <...;" + "score: ").append(sd.score).append("<br>
can't read my xml file in java
(); } the codes can't read the xml file bcz i want to append the whole xml in my gui...can't read my xml file in java  i've a xml file like this : <...;" + "score: ").append(sd.score).append("<br>
can't read my xml file in java
(); } the codes can't read the xml file bcz i want to append the whole xml in my gui...can't read my xml file in java  i've a xml file like this : <...;" + "score: ").append(sd.score).append("<br>
can't read my xml file in java
(); } the codes can't read the xml file bcz i want to append the whole xml in my gui...can't read my xml file in java  i've a xml file like this : <...;" + "score: ").append(sd.score).append("<br>
XML
XML  How i remove a tag from xml and update it in my xml
php array append
append function is used to add the element in the last position... Example of PHP Array Append Function <?php $ar1=new ArrayObject... ($ar1 as $a) echo $a." "; $ar1->append("ddd");ADS
how to write append file in Java
how to write append file in Java  How to write append file in Java   Hi, For append in the test new file or Appending a text earlier...("appenToFile.txt", true); For More Details visit this link: How to Append file
JDOM CDATA Example, Use of append(String str) method of CDATA class.
) method will append character data with in this CDATA node. In this example... JDOM CDATA Example, Use of append(String str) method of CDATA class. In this tutorial, we will implement append() method of  CDATA class
xml
xml  why the content written in xml is more secure
xml
xml  validate student login using xml for library management system
xml
xml  validate student login using xml for library management system
xml
xml  what is name space,xml scema give an example for each   XML Namespaces provide a method to avoid element name conflicts.They are used for providing uniquely named elements and attributes in an XML document
MySQL Append Data
MySQL Append Data This example illustrates how to append data with a column value. In this example we use 'CONCAT' function to append data to the column value. Table
XML
XML  please tell me how i remove one tag out of all similar type of tags in xml

Ads