Java--Xml Modify Node Value

Java--Xml Modify Node Value

View Answers

December 9, 2009 at 12:58 PM

Hi,
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.
/**
* Writes the Document object into an XML file.
*/
public static void createXMLFile(Document doc, File fileName)
{
try
{
OutputFormat format = new OutputFormat(doc);
format.setIndenting(true);
XMLSerializer output = new XMLSerializer(new FileOutputStream(fileName), format);
output.serialize(doc);
System.out.println("File updated");
}
catch(Exception e){
e.printStackTrace();
}
}

Call this method after updationg node is completed.

Try this. I think this will help you.

December 9, 2009 at 1:26 PM

Thanks for your reply...its not working....Actually I could not even able to retrieve the element name inside the for loop...I am going wrong in the following lines..please correct me

NodeList list = doc.getElementsByTagName("*");

for (int i=0; i<list.getLength(); i++) {
// Get element
Element element = (Element)list.item(i);
System.out.println(element.getNodeName());

element.setTextContent("Prasanna");
System.out.println(element.getNodeName());
}
}
No Elements are getting printd to Console..Please help me in this regard...

December 9, 2009 at 4:56 PM

Hi,

The above code works if the updation is successful. That code is not for getting the node values.


Whenever you are trying to update a node, first you need to check whether it is text node or element node.
If xml is like: <node1>
<node2>sample text</node2>
</node1>

Here node2 is text node and node1 is element node.

setTextcontent() is for updating value in text nodes only. If you do this for element nodes , all nodes under element node are deleted and replaced with specified text content.


Here you are using:
//The following loop iterates only once even though you are gettting node list length 5.
for (int i=0; i<list.getLength(); i++) {
Node element = (Node)list.item(i); //When i=0, This gives root node object <or:AddOrder> as as single node
System.out.println("ele: "+element.getNodeName()); //This gives output as <or:AddOrder> as the first node is <or:AddOrder>
element.setTextContent("Prasanna"); //With this line, all nodes under <or:AddOrder> suppressed and replaced with Prasanna text ie., it changed as : <or:AddOrder>Prasanna</or:AddOrder>. So it wont iterate further.

/*
Here you need put a condition and set text as follows: Replace the above line with following code:

if(element.getNodeName().equals("BuyersID") || element.getNodeName().equals("utcc:IssueDateTime") || element.getNodeName().equals("utcc:KCIType"))
System.out.println("node name: "+element.getNodeName()+"node text:"+element.getTextContent());
//Now set text content as u done above
element.setTextContent("Prasanna"); //This replaces text content for all the mentioned nodes. If you dont need that, put each node name in separate 'if' and do as you need for each node.
}*/

}

Instead of iterating all nodes using *, better getting the node list by specifying tag name.

For example,
if you want to retrieve the values of <BuyersID>,<utcc:IssueDateTime>,and <utcc:KCIType> through NodeList use the following code:

If you know the xml content( ie., if xml is not getting prepared at runtime) before accessing it, try to retrieve the node values as below:
//Getting all <BuyersID> nodes.

NodeList list = doc.getElementsByTagName("BuyersID");

for (int i=0; i<list.getLength(); i++) {
System.out.println("list lenght: "+list.getLength());
// Get element
Node element = (Node)list.item(i);
System.out.println("node Name:: "+element.getNodeName()+" node text content:"+element.getTextContent()); //Here you will get values as <BuyersID> is text node.

//Update the node here if you want.
}

December 9, 2009 at 6:19 PM

Really thanks a lot for your patient reply.....Its working now...

I wish you a bright professional career ahead...

Once again thanks a lot...









Related Tutorials/Questions & Answers:
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
Java-Xml -Modify and Update Node - Java Beginners
Java-Xml -Modify and Update Node   test_final_1 2009-025T13:23...(); } } I want to modify the values of and in the above xml posted and update...(); System.out.println("XML Data: "); DefaultHandler dHandler = new
Advertisements
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 the value of and (ie) test_final_1,2009-025T13:23:45 respectively. I have
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
Determining If a Preference Node Contains a Specific Value
checks whether the Preference node 'Java Types' contains the specified value... Determining If a Preference Node Contains a Specific Value... or not by enumerating the key/value pairs in a preference node and checks each value for a match
modify program
modify program  Hi how could I modify this program so that if I say yes for the dialog the following prompt would be displayed for the user to enter the information and would stop if no is selected.As the program is now if I say
Java XML modification
Java XML modification This section explain you how to modify the xml file..., DocumentBuilder and Document classes to get the default DOM parser and parse the xml file. Then call the function delNode() that finds the specified node from the node
how to modify QuestionServlet.java page?
how to modify QuestionServlet.java page?  Dear frnds, how to modify existing QuestionServlet. java file
date_modify
date_modify() in PHP date_modify or DateTime::modify function modifies... by strtotime(). It returns the modify date time. Description public DateTime DateTime::modify ( string $modify ) DateTime date_modify ( DateTime $object
how to store,retrieve,modify the data
how to store,retrieve,modify the data  hello sir ,how to store,retrieve,modify the data using the swing please help me
ModuleNotFoundError: No module named 'pdfconduit-modify'
ModuleNotFoundError: No module named 'pdfconduit-modify'  Hi, My... named 'pdfconduit-modify' How to remove the ModuleNotFoundError: No module named 'pdfconduit-modify' error? Thanks   Hi, In your
Modify Data Type with ALTER Command
Modify Data Type with ALTER Command  Is it possible to modify... EmpName INT; Is it possible to modify the above table like... the following query: ALTER TABLE Emp MODIFY EmpName int(255
how to modify content of XML file
how to modify content of XML file  hi, I want to modify content of a xml file.There are two tags of similar name say <ContentName>C:\Myinfo... to xml file to replace "XYZ".Every time with the content of text box the file should
how to modify hosts file in ubuntu
how to modify hosts file in ubuntu  Hi, I want to add few host names with ip address in Ubuntu. how to modify hosts file in ubuntu? Thanks  ... modify hosts file in Ubunut. Thanks
Is it modify Object data? Generally Object data can't modify............but in this program it modifies.......... Why?
Is it modify Object data? Generally Object data can't modify... integer value: "); a=Integer.parseInt(dis.readLine()); //Fundamental... conversion"); System.out.println("a+10 value: "+(a+10)+"\t\t\ta+20 value: "+(a+20
can modify this application connection with database
can modify this application connection with database   hi i'm want to say who thank java master or java professional help me convert Java applet to Java Frame, in here can i ask one more question about using this application
ModuleNotFoundError: No module named 'modify-csi-datatable'
ModuleNotFoundError: No module named 'modify-csi-datatable'  Hi...: No module named 'modify-csi-datatable' How to remove the ModuleNotFoundError: No module named 'modify-csi-datatable' error? Thanks   Hi
ModuleNotFoundError: No module named 'django-modify-history'
ModuleNotFoundError: No module named 'django-modify-history'  Hi...: No module named 'django-modify-history' How to remove the ModuleNotFoundError: No module named 'django-modify-history' error? Thanks   Hi
ModuleNotFoundError: No module named 'modify-csi-datatable'
ModuleNotFoundError: No module named 'modify-csi-datatable'  Hi...: No module named 'modify-csi-datatable' How to remove the ModuleNotFoundError: No module named 'modify-csi-datatable' error? Thanks   Hi
How can i modify my account in roseindia
How can i modify my account in roseindia  Presently am not using my gmail id. I have to modify my roseindia account. Please send the answer to following mail id
Node class
Node class   hii, What is a node class?   hello,ADS_TO_REPLACE_1 A node class is a class that has added new services or functionality beyond the services inherited from its base class
java with xml parsing - Java Beginners
java with xml parsing  Hi, I need the sample code for parsing complex data xml file with java code. Example product,category,subcategory these type of xml files and parse using java. Please send the code immediately its very
Java-XML-DOM - XML
Java-XML-DOM  Hi! I need some help. I have to make java program that loads an xml file and from it builds DOM(later i will have to work with it - like using xpath in java find some value and replace it...). Since i'm new to java
Listening for Changes to Preference Values in a Preference Node
in the node. prefs.remove("key")- This method will removes the value... Listening for Changes to Preference Values in a Preference Node... to change the Preference values in a Preference node. You can see in the given
java - XML
in the XML document while i am parsing the file using SAX event based parser. In the method startElement(), i would to like to add the attribute value to the element.... provide the way in java.  Hi Friend, Try the following code: import
XML with JAVA - XML
a particular node within XML document" . Explanation of program:- input must be in XML document and the processing in JAVA program . Find the time for each XML element...XML with JAVA  Hi.. This is Priya here. Thanks for responding me. I
Xml append node problem
Xml append node problem   print("code sample");Question: I create... to Node. Output: 111 ---> <?xml version="1.0" ?><cwMin>31<..." which is of type org.w3c.dom.Node. and the value of "nd" is : <?xml version
ModuleNotFoundError: No module named 'ansible-role-tripleo-modify-image'
ModuleNotFoundError: No module named 'ansible-role-tripleo-modify-image' ...: ModuleNotFoundError: No module named 'ansible-role-tripleo-modify-image' How to remove the ModuleNotFoundError: No module named 'ansible-role-tripleo-modify-image'
ModuleNotFoundError: No module named 'ansible-role-tripleo-modify-image'
ModuleNotFoundError: No module named 'ansible-role-tripleo-modify-image' ...: ModuleNotFoundError: No module named 'ansible-role-tripleo-modify-image' How to remove the ModuleNotFoundError: No module named 'ansible-role-tripleo-modify-image'
ModuleNotFoundError: No module named 'ansible-role-tripleo-modify-image'
ModuleNotFoundError: No module named 'ansible-role-tripleo-modify-image' ...: ModuleNotFoundError: No module named 'ansible-role-tripleo-modify-image' How to remove the ModuleNotFoundError: No module named 'ansible-role-tripleo-modify-image'
Read XML in java - XML
Read XML in java  Hi Deepak, I want to read a xml file which have... a solution.my java code is given below. import java.io.File; import...; nodeLst.getLength(); s++) { Node fstNode = nodeLst.item(s); Node
Java XML modification - Java Beginners
Java XML modification  hey I want to delete the nodes in Xml file & that should be updated in xml file.here is what i have tried. import...; listofmenus.getLength(); i++) { Node testcase = listofmenus.item(i); NodeList nodelist1
by value or by reference
by value or by reference  Are objects passed by value or by reference
ModuleNotFoundError: No module named 'node'
ModuleNotFoundError: No module named 'node'  Hi, My Python program is throwing following error: ModuleNotFoundError: No module named 'node' How to remove the ModuleNotFoundError: No module named 'node' error
Removing a Preference from a Preference Node
(key-value associations) from the preference node. Here is the code... Removing a Preference from a Preference Node  ... the preference from a preference node. You can see in the given example
Need someone to check and modify my simple code - Java Beginners
Need someone to check and modify my simple code   How to write a class that contains Variables that hold hourly rate of pay, number of hours..., "Enter numeric value"); } } }); } public static void main(String
objective c pass by value
; //j now == 23, but this hasn't changed the value of i. } If you wanted to be able to modify i, you would have to pass the value of the reference by doing...objective c pass by value   How to pass value by reference
Java-XML Xerces/Jaxp
Java-XML Xerces/Jaxp  Im new to Java DOM development. I have doubt or I am bit unclear about fact of JAXP and Xerces. My question is why developer use xerces when jaxp does the job
Java-XML Xerces/Jaxp
Java-XML Xerces/Jaxp  Im new to Java DOM development. I have doubt or I am bit unclear about fact of JAXP and Xerces. My question is why developer use xerces when jaxp does the job
Please help me to modify my java code from php code
Please help me to modify my java code from php code  i want to covert this php code int java/JSP . if (isset($_POST['orders'])) { $orders... help me to convert it into Java. if (request.getParameter("orders") != null
Version of com.nfbsoftware>java-xml dependency
List of Version of com.nfbsoftware>java-xml dependency
the value of $$b
the value of $$b  If the variable $a is equal to 5 and variable $b is equal to character a, what?s the value of $$b
XML in java - XML
XML in java  Write a program using SAX that will count the number of occurrences of each element type in an XML document and display them... argument.Then modify the program resulting from the this exercise so that it will accept
PASS value
PASS value  javascript to pass value to other html file
Java Xml Data Store
Java Xml Data Store  I have to do this project and i'm finding it so hard its way over my head if any one has any ideas or help. What would the best... or XML file. As a good Java programmer you will use correct Object-Oriented
Java XML parser
Java XML parser  Hi friends, i am new to java XML parsing. i need to parse the following xml response which i got from a url hit: <response> <status>SUCCESS</status> <app-config> <CHECK_LOW_SCORE>
node dependency mysql package.json
node dependency mysql package.json  Hi, How to add node dependency mysql package.json? Thanks   Hi, You can do this by running following command in your project: npm install mysql --save Thanks
node dependency mysql package.json
node dependency mysql package.json  Hi, How to add node dependency mysql package.json? Thanks   Hi, You can do this by running following command in your project: npm install mysql --save Thanks
Java + XML - XML
java...the attribute value..not sure now how to read the xml file passing...Java + XML  1) I have some XML files, read one xml..." pointing to a hello xml file ..read that file and get the value of the parent
JavaScript getAttributeNode method
the attribute node value. It can be used to retrieve the attribute node reference..." value="Get Attribute Node(ID)" onclick="getAttributeNodeID();"> <input type="button" value="Get Attribute Node(Align)" onclick="getAttributeNodeAlign

Ads