Xml append node problem

Ads
 

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);
        }
    }
}

Ads









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 problem - XML
xml problem  URGENT>>>>> how to retrieve data from hash tables without a JDBC connection?????? Thanks & Regards SAIBHARGAV146
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
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
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
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
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
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
DOM Example For Creating a Child Node 
;) and append this child with the root node. In this last step, we create... 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
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
Java get Node Text
of the node in the specified XML file. For this we have create a 'employee.xml' file...;employee.xml".In order to get the text of the node specified in a XML file, we... of GetNodeText.java you get the text of the node specified in "employee.xml" xml
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
XML
XML  How i remove a tag from xml and update it in my xml
Convert Text To XML
the root and child node into xml file. Pass  array string as value of nodes... Convert Text To XML       Here we are discussing the conversion of a text file into xml
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
Creating a Preference Node
Creating a Preference Node       This section demonstrates you to create a Preference Node... Node and System Preference Node. Here we are going to create a user preference
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
XML
XML  please tell me how i remove one tag out of all similar type of tags in xml
xml
xml  how can i remove white space and next line when i copy stream to xml file
XML
XML  create flat file with 20 records. Read the records using xml parser and show required details
xml
xml  what is xml   Extensible Markup Language (XML... that is both human-readable and machine-readable. It is defined in the XML 1.0... gratis open standards. The design goals of XML emphasize simplicity, generality
tree menu delete node
nodes now i want to delete parent node and also want to delete sub nodes when parent node is deleted........i am using servlet and giving nodeid to servlet using url ....i have a problem when i perform a delete operation on parent 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.   Query   SELECT
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
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
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
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>

Ads