XML is Extensible Markup Language. It has root node and elements. Once it’s elements created, it stored in .xml file.
When you
want to update the file, use java language to make it effective manner.
Let us create
a XML file for students.
- A xml file version is assigned as 1.0,encoding type is “UTF-8”.
- Here,the root node is students.
- Elements are name, class, grade.
- All tags are opened and closed.
“students.xml”
<?xml
version="1.0" encoding="UTF-8"
standalone="no"?>
<students>
<student id="s_1">
<name>Aarvi</name>
<class>7 </class>
<grade>A++</grade>
</student>
</students>
Java program to update XML file:
To implement this in java, use the
built in packages javax.xm.parsers and xml.tranform,java.io.File and
org.w3c.dom and its sub packages.
- Create a public class with main() function.
- A new file object instance is created and it point out ‘students.xml’.
- Three more objects are created for documentbuilder,documentbuilderfactory and document.
- First element of xml file is extracted and its ‘name’ tag is assigned with new value.
- To update this in file,four more objects created for transformfactory,transformer,DOMSource and StreamResult.
- To transform the data from source to destination,transform() function is used.
- Finally,it displays the updated message.
Program:
import
javax.xml.parsers.DocumentBuilderFactory;
import
javax.xml.parsers.DocumentBuilder;
import
org.w3c.dom.*;
import
javax.xml.transform.*;
import
javax.xml.transform.dom.DOMSource;
import
javax.xml.transform.stream.StreamResult;
import
java.io.File;
public
class UpdateXMLEg {
public static void main(String[] args) {
try {
File file1 = new
File("students.xml");
DocumentBuilderFactory factory1 =
DocumentBuilderFactory.newInstance();
DocumentBuilder builder1 =
factory1.newDocumentBuilder();
Document doc1 =
builder1.parse(file1);
Element student = (Element)
doc1.getElementsByTagName("student").item(0);
student.getElementsByTagName("name").item(0).setTextContent("arthi");
// Update name
TransformerFactory
transformerFactory1 = TransformerFactory.newInstance();
Transformer transformer1 =
transformerFactory1.newTransformer();
DOMSource source1 = new
DOMSource(doc1);
StreamResult result = new
StreamResult(file1);
transformer1.transform(source1,
result);
System.out.println("The XML
File is Updated!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
Compile and
run the program to get the output.
C:\raji\blog>javac
UpdateXMLEg.java
C:\raji\blog>java UpdateXMLEg
The XML
File is Updated!
The xml
file is changed the name
This is the
way of updating XML file using java is implemented. Hope this code will helpful
to you.
No comments:
Post a Comment