SlideShare a Scribd company logo
DOM
How to print the xml
elements(nodes) as ordered list
Index.xml
<?xml version="1.0"?>
<class>
<student rollno="393">
<firstname>dinkar</firstname>
<lastname>kad</lastname>
<nickname>dinkar</nickname>
<marks>85</marks>
</student>
<student rollno="493">
<firstname>Vaneet</firstname>
<lastname>Gupta</lastname>
<nickname>vinni</nickname>
<marks>95</marks>
</student>
<student rollno="593">
<firstname>jasvir</firstname>
<lastname>singn</lastname>
<nickname>jazz</nickname>
<marks>90</marks>
</student>
</class>
DomParserDemo.java
import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
public class DomParserDemo
{
public static void main(String[] args){
try {
inputFile = new File("input.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputFile);
doc.getDocumentElement().normalize();
The normalize() method merges adjacent text() nodes and removes empty ones in the
whole document.
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
//returns a list of subelements of specified name
NodeList nList = doc.getElementsByTagName("student");
System.out.println("----------------------------");
for (int temp = 0; temp < nList.getLength(); temp++)
{
Node nNode = nList.item(temp);
System.out.println("nCurrent Element :" + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE)// check for element node
{
Element eElement = (Element) nNode;
System.out.println("Student roll no : " + eElement.getAttribute("rollno"));
System.out.println(“First Name : " + eElement.getElementsByTagName(“firstname") .item(0) .getTextContent());
System.out.println("Last Name : " + eElement.getElementsByTagName("lastname") .item(0) .getTextContent());
System.out.println(“Nick Name : " + eElement.getElementsByTagName("nickname") .item(0) .getTextContent());
System.out.println(“Marks: " + eElement.getElementsByTagName("marks") .item(0) .getTextContent());
}
}
}
catch (Exception e)
{
e.printStackTrace(); //useful tool for diagnosing an Exception
}
}
}
Output will be
Root element :class
----------------------------
Current Element :student
Student roll no : 393
First Name : dinkar
Last Name : kad
Nick Name : dinkarMarks : 85
Current Element :student
Student roll no : 493
First Name : Vaneet
Last Name : Gupta
Nick Name : vinniMarks : 95
Current Element :student
Student roll no : 593
First Name : jasvir
Last Name : singh
Nick Name : jazz
Marks : 90
How to create the xml document
import javax.xml.parsers.*;
import javax.xml.transform.*;
import org.w3c.dom.*;
import java.io.*;
public class CreateXmlFileDemo
{
public static void main(String argv[])
{ try
{
DocumentBuilderFactory dbFactory =DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.newDocument();
// root element
Element rootElement = doc.createElement("cars");
doc.appendChild(rootElement); // supercars element
Element supercar = doc.createElement("supercars");
rootElement.appendChild(supercar); // setting attribute to element
Attr attr = doc.createAttribute("company");
attr.setValue("Ferrari");
supercar.setAttributeNode(attr); // carname element
Element carname = doc.createElement("carname");
Attr attrType = doc.createAttribute("type");
attrType.setValue("formula one");
carname.setAttributeNode(attrType);
carname.appendChild( doc.createTextNode("Ferrari 101"));
supercar.appendChild(carname);
Element carname1 = doc.createElement("carname");
Attr attrType1 = doc.createAttribute("type");
attrType1.setValue("sports");
carname1.setAttributeNode(attrType1);
carname1.appendChild(doc.createTextNode("Ferrari 202"));
supercar.appendChild(carname1);
// write the content into xml file
TransformerFactory transformerFactory= TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("C:cars.xml"));
transformer.transform(source, result); // Output to console for testing
StreamResult consoleResult =new StreamResult(System.out);
transformer.transform(source, consoleResult);
}
catch (Exception e)
{
e.printStackTrace();
} }}
OUTPUT will be
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<cars>
<supercars company="Ferrari">
<carname type="formula one">Ferrari 101</carname>
<carname type="sports">Ferrari 202</carname>
</supercars>
</cars>
(you will have cars.xml created in C:>
How to modify the xmldocument
Original XML file(input.xml)
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<cars>
<supercars company="Ferrari">
<carname type="formula one">Ferrari 101</carname>
<carname type="sports">Ferrari 202</carname>
</supercars>
<luxurycars company="Benteley">
<carname>Benteley 1</carname>
<carname>Benteley 2</carname>
<carname>Benteley 3</carname>
</luxurycars>
</cars>
import java.io.File;
import javax.xml.parsers.*;I
import javax.xml.transform.*;
import org.w3c.dom.*;
public class ModifyXmlFileDemo
{ public static void main(String argv[])
{ try {
File inputFile = new File("input.xml");
DocumentBuilderFactory docFactory =
DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(inputFile);
Node cars = doc.getFirstChild();
Node supercar = doc.getElementsByTagName("supercars").item(0); //
update supercar attribute
NamedNodeMap attr = supercar.getAttributes();
Node nodeAttr = attr.getNamedItem("company");
nodeAttr.setTextContent("Lamborigini"); // loop the supercar child node
NodeList list = supercar.getChildNodes();
for (int temp = 0; temp < list.getLength(); temp++)
{
Node node = list.item(temp);
if (node.getNodeType() == Node.ELEMENT_NODE)
{
Element eElement = (Element) node;
if ("carname".equals(eElement.getNodeName()))
{
if("Ferrari 101".equals(eElement.getTextContent()))
{
eElement.setTextContent("Lamborigini 001");
}
if("Ferrari 202".equals(eElement.getTextContent()))
eElement.setTextContent("Lamborigini 002");
}
}
}
NodeList childNodes = cars.getChildNodes();
for(int count = 0; count < childNodes.getLength(); count++)
{
Node node = childNodes.item(count);
if("luxurycars".equals(node.getNodeName()))
cars.removeChild(node);
} // write the content on console
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
System.out.println("-----------Modified File-----------");
StreamResult consoleResult = new StreamResult(System.out);
transformer.transform(source, consoleResult);
}
catch (Exception e)
{ e.printStackTrace();
} }}
Output will be
-----------Modified File-----------
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<cars>
<supercars company="Lamborigini">
<carname type="formula one">Lamborigini 001</carname>
<carname type="sports">Lamborigini 002</carname>
</supercars>
</cars>

More Related Content

What's hot

My sql presentation
My sql presentationMy sql presentation
My sql presentation
Nikhil Jain
 
ECMAScript2015
ECMAScript2015ECMAScript2015
ECMAScript2015
qmmr
 
PofEAA and SQLAlchemy
PofEAA and SQLAlchemyPofEAA and SQLAlchemy
PofEAA and SQLAlchemy
Inada Naoki
 

What's hot (20)

Views notwithstanding
Views notwithstandingViews notwithstanding
Views notwithstanding
 
Introducción rápida a SQL
Introducción rápida a SQLIntroducción rápida a SQL
Introducción rápida a SQL
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technology
 
Shortcodes In-Depth
Shortcodes In-DepthShortcodes In-Depth
Shortcodes In-Depth
 
Python Ireland Nov 2010 Talk: Unit Testing
Python Ireland Nov 2010 Talk: Unit TestingPython Ireland Nov 2010 Talk: Unit Testing
Python Ireland Nov 2010 Talk: Unit Testing
 
Make your own wp cli command in 10min
Make your own wp cli command in 10minMake your own wp cli command in 10min
Make your own wp cli command in 10min
 
PHP tips and tricks
PHP tips and tricks PHP tips and tricks
PHP tips and tricks
 
November Camp - Spec BDD with PHPSpec 2
November Camp - Spec BDD with PHPSpec 2November Camp - Spec BDD with PHPSpec 2
November Camp - Spec BDD with PHPSpec 2
 
My sql presentation
My sql presentationMy sql presentation
My sql presentation
 
ECMAScript2015
ECMAScript2015ECMAScript2015
ECMAScript2015
 
ATK 'Beyond The Pizza Guides'
ATK 'Beyond The Pizza Guides'ATK 'Beyond The Pizza Guides'
ATK 'Beyond The Pizza Guides'
 
Bag Of Tricks From Iusethis
Bag Of Tricks From IusethisBag Of Tricks From Iusethis
Bag Of Tricks From Iusethis
 
PofEAA and SQLAlchemy
PofEAA and SQLAlchemyPofEAA and SQLAlchemy
PofEAA and SQLAlchemy
 
Why ruby
Why rubyWhy ruby
Why ruby
 
Ruby/Rails
Ruby/RailsRuby/Rails
Ruby/Rails
 
A Tour to MySQL Commands
A Tour to MySQL CommandsA Tour to MySQL Commands
A Tour to MySQL Commands
 
Building secured wordpress themes and plugins
Building secured wordpress themes and pluginsBuilding secured wordpress themes and plugins
Building secured wordpress themes and plugins
 
PHP 5.3 and Lithium: the most rad php framework
PHP 5.3 and Lithium: the most rad php frameworkPHP 5.3 and Lithium: the most rad php framework
PHP 5.3 and Lithium: the most rad php framework
 
Wordpress plugin development from Scratch
Wordpress plugin development from ScratchWordpress plugin development from Scratch
Wordpress plugin development from Scratch
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of Lithium
 

Similar to DOM PARSER

international PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnitinternational PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
smueller_sandsmedia
 
Metaprogramovanie #1
Metaprogramovanie #1Metaprogramovanie #1
Metaprogramovanie #1
Jano Suchal
 
Laying the proper foundation for plugin and theme development
Laying the proper foundation for plugin and theme developmentLaying the proper foundation for plugin and theme development
Laying the proper foundation for plugin and theme development
Tammy Hart
 
#NewMeetup Performance
#NewMeetup Performance#NewMeetup Performance
#NewMeetup Performance
Justin Cataldo
 

Similar to DOM PARSER (20)

PhpUnit - The most unknown Parts
PhpUnit - The most unknown PartsPhpUnit - The most unknown Parts
PhpUnit - The most unknown Parts
 
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnitinternational PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownparts
 
Code me a HR
Code me a HRCode me a HR
Code me a HR
 
Broadleaf Presents Thymeleaf
Broadleaf Presents ThymeleafBroadleaf Presents Thymeleaf
Broadleaf Presents Thymeleaf
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownparts
 
Clean Javascript
Clean JavascriptClean Javascript
Clean Javascript
 
Modules and injector
Modules and injectorModules and injector
Modules and injector
 
Nativescript angular
Nativescript angularNativescript angular
Nativescript angular
 
Metaprogramovanie #1
Metaprogramovanie #1Metaprogramovanie #1
Metaprogramovanie #1
 
Advanced symfony Techniques
Advanced symfony TechniquesAdvanced symfony Techniques
Advanced symfony Techniques
 
Kicking off with Zend Expressive and Doctrine ORM (PHP UK 2017)
Kicking off with Zend Expressive and Doctrine ORM (PHP UK 2017)Kicking off with Zend Expressive and Doctrine ORM (PHP UK 2017)
Kicking off with Zend Expressive and Doctrine ORM (PHP UK 2017)
 
Kicking off with Zend Expressive and Doctrine ORM (Sunshine PHP 2017)
Kicking off with Zend Expressive and Doctrine ORM (Sunshine PHP 2017)Kicking off with Zend Expressive and Doctrine ORM (Sunshine PHP 2017)
Kicking off with Zend Expressive and Doctrine ORM (Sunshine PHP 2017)
 
Power shell examples_v4
Power shell examples_v4Power shell examples_v4
Power shell examples_v4
 
Laying the proper foundation for plugin and theme development
Laying the proper foundation for plugin and theme developmentLaying the proper foundation for plugin and theme development
Laying the proper foundation for plugin and theme development
 
And the Greatest of These Is ... Rack Support
And the Greatest of These Is ... Rack SupportAnd the Greatest of These Is ... Rack Support
And the Greatest of These Is ... Rack Support
 
Practica n° 7
Practica n° 7Practica n° 7
Practica n° 7
 
#NewMeetup Performance
#NewMeetup Performance#NewMeetup Performance
#NewMeetup Performance
 
Migrare da symfony 1 a Symfony2
 Migrare da symfony 1 a Symfony2  Migrare da symfony 1 a Symfony2
Migrare da symfony 1 a Symfony2
 
Learn Dart And Angular, Get Your Web Development Wings With Kevin Moore
Learn Dart And Angular, Get Your Web Development Wings With Kevin MooreLearn Dart And Angular, Get Your Web Development Wings With Kevin Moore
Learn Dart And Angular, Get Your Web Development Wings With Kevin Moore
 

Recently uploaded

CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxCFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
R&R Consult
 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
Neometrix_Engineering_Pvt_Ltd
 
Hall booking system project report .pdf
Hall booking system project report  .pdfHall booking system project report  .pdf
Hall booking system project report .pdf
Kamal Acharya
 
RS Khurmi Machine Design Clutch and Brake Exercise Numerical Solutions
RS Khurmi Machine Design Clutch and Brake Exercise Numerical SolutionsRS Khurmi Machine Design Clutch and Brake Exercise Numerical Solutions
RS Khurmi Machine Design Clutch and Brake Exercise Numerical Solutions
Atif Razi
 

Recently uploaded (20)

KIT-601 Lecture Notes-UNIT-5.pdf Frame Works and Visualization
KIT-601 Lecture Notes-UNIT-5.pdf Frame Works and VisualizationKIT-601 Lecture Notes-UNIT-5.pdf Frame Works and Visualization
KIT-601 Lecture Notes-UNIT-5.pdf Frame Works and Visualization
 
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxCFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
 
Peek implant persentation - Copy (1).pdf
Peek implant persentation - Copy (1).pdfPeek implant persentation - Copy (1).pdf
Peek implant persentation - Copy (1).pdf
 
Online resume builder management system project report.pdf
Online resume builder management system project report.pdfOnline resume builder management system project report.pdf
Online resume builder management system project report.pdf
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
 
Hall booking system project report .pdf
Hall booking system project report  .pdfHall booking system project report  .pdf
Hall booking system project report .pdf
 
Halogenation process of chemical process industries
Halogenation process of chemical process industriesHalogenation process of chemical process industries
Halogenation process of chemical process industries
 
The Ultimate Guide to External Floating Roofs for Oil Storage Tanks.docx
The Ultimate Guide to External Floating Roofs for Oil Storage Tanks.docxThe Ultimate Guide to External Floating Roofs for Oil Storage Tanks.docx
The Ultimate Guide to External Floating Roofs for Oil Storage Tanks.docx
 
fluid mechanics gate notes . gate all pyqs answer
fluid mechanics gate notes . gate all pyqs answerfluid mechanics gate notes . gate all pyqs answer
fluid mechanics gate notes . gate all pyqs answer
 
Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.
 
RS Khurmi Machine Design Clutch and Brake Exercise Numerical Solutions
RS Khurmi Machine Design Clutch and Brake Exercise Numerical SolutionsRS Khurmi Machine Design Clutch and Brake Exercise Numerical Solutions
RS Khurmi Machine Design Clutch and Brake Exercise Numerical Solutions
 
KIT-601 Lecture Notes-UNIT-4.pdf Frequent Itemsets and Clustering
KIT-601 Lecture Notes-UNIT-4.pdf Frequent Itemsets and ClusteringKIT-601 Lecture Notes-UNIT-4.pdf Frequent Itemsets and Clustering
KIT-601 Lecture Notes-UNIT-4.pdf Frequent Itemsets and Clustering
 
ENERGY STORAGE DEVICES INTRODUCTION UNIT-I
ENERGY STORAGE DEVICES  INTRODUCTION UNIT-IENERGY STORAGE DEVICES  INTRODUCTION UNIT-I
ENERGY STORAGE DEVICES INTRODUCTION UNIT-I
 
A case study of cinema management system project report..pdf
A case study of cinema management system project report..pdfA case study of cinema management system project report..pdf
A case study of cinema management system project report..pdf
 
KIT-601 Lecture Notes-UNIT-3.pdf Mining Data Stream
KIT-601 Lecture Notes-UNIT-3.pdf Mining Data StreamKIT-601 Lecture Notes-UNIT-3.pdf Mining Data Stream
KIT-601 Lecture Notes-UNIT-3.pdf Mining Data Stream
 
NO1 Pandit Amil Baba In Bahawalpur, Sargodha, Sialkot, Sheikhupura, Rahim Yar...
NO1 Pandit Amil Baba In Bahawalpur, Sargodha, Sialkot, Sheikhupura, Rahim Yar...NO1 Pandit Amil Baba In Bahawalpur, Sargodha, Sialkot, Sheikhupura, Rahim Yar...
NO1 Pandit Amil Baba In Bahawalpur, Sargodha, Sialkot, Sheikhupura, Rahim Yar...
 
Architectural Portfolio Sean Lockwood
Architectural Portfolio Sean LockwoodArchitectural Portfolio Sean Lockwood
Architectural Portfolio Sean Lockwood
 
WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234
 
BRAKING SYSTEM IN INDIAN RAILWAY AutoCAD DRAWING
BRAKING SYSTEM IN INDIAN RAILWAY AutoCAD DRAWINGBRAKING SYSTEM IN INDIAN RAILWAY AutoCAD DRAWING
BRAKING SYSTEM IN INDIAN RAILWAY AutoCAD DRAWING
 

DOM PARSER

  • 1. DOM
  • 2. How to print the xml elements(nodes) as ordered list
  • 3. Index.xml <?xml version="1.0"?> <class> <student rollno="393"> <firstname>dinkar</firstname> <lastname>kad</lastname> <nickname>dinkar</nickname> <marks>85</marks> </student> <student rollno="493"> <firstname>Vaneet</firstname> <lastname>Gupta</lastname> <nickname>vinni</nickname> <marks>95</marks> </student> <student rollno="593"> <firstname>jasvir</firstname> <lastname>singn</lastname> <nickname>jazz</nickname> <marks>90</marks> </student> </class>
  • 4. DomParserDemo.java import java.io.*; import javax.xml.parsers.*; import org.w3c.dom.*; public class DomParserDemo { public static void main(String[] args){ try { inputFile = new File("input.xml"); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(inputFile); doc.getDocumentElement().normalize(); The normalize() method merges adjacent text() nodes and removes empty ones in the whole document. System.out.println("Root element :" + doc.getDocumentElement().getNodeName()); //returns a list of subelements of specified name NodeList nList = doc.getElementsByTagName("student"); System.out.println("----------------------------");
  • 5. for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); System.out.println("nCurrent Element :" + nNode.getNodeName()); if (nNode.getNodeType() == Node.ELEMENT_NODE)// check for element node { Element eElement = (Element) nNode; System.out.println("Student roll no : " + eElement.getAttribute("rollno"));
  • 6. System.out.println(“First Name : " + eElement.getElementsByTagName(“firstname") .item(0) .getTextContent()); System.out.println("Last Name : " + eElement.getElementsByTagName("lastname") .item(0) .getTextContent()); System.out.println(“Nick Name : " + eElement.getElementsByTagName("nickname") .item(0) .getTextContent()); System.out.println(“Marks: " + eElement.getElementsByTagName("marks") .item(0) .getTextContent()); } } } catch (Exception e) { e.printStackTrace(); //useful tool for diagnosing an Exception } } }
  • 7. Output will be Root element :class ---------------------------- Current Element :student Student roll no : 393 First Name : dinkar Last Name : kad Nick Name : dinkarMarks : 85 Current Element :student Student roll no : 493 First Name : Vaneet Last Name : Gupta Nick Name : vinniMarks : 95 Current Element :student Student roll no : 593 First Name : jasvir Last Name : singh Nick Name : jazz Marks : 90
  • 8. How to create the xml document
  • 9. import javax.xml.parsers.*; import javax.xml.transform.*; import org.w3c.dom.*; import java.io.*; public class CreateXmlFileDemo { public static void main(String argv[]) { try { DocumentBuilderFactory dbFactory =DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.newDocument(); // root element Element rootElement = doc.createElement("cars"); doc.appendChild(rootElement); // supercars element Element supercar = doc.createElement("supercars"); rootElement.appendChild(supercar); // setting attribute to element Attr attr = doc.createAttribute("company"); attr.setValue("Ferrari");
  • 10. supercar.setAttributeNode(attr); // carname element Element carname = doc.createElement("carname"); Attr attrType = doc.createAttribute("type"); attrType.setValue("formula one"); carname.setAttributeNode(attrType); carname.appendChild( doc.createTextNode("Ferrari 101")); supercar.appendChild(carname); Element carname1 = doc.createElement("carname"); Attr attrType1 = doc.createAttribute("type"); attrType1.setValue("sports"); carname1.setAttributeNode(attrType1); carname1.appendChild(doc.createTextNode("Ferrari 202")); supercar.appendChild(carname1);
  • 11. // write the content into xml file TransformerFactory transformerFactory= TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File("C:cars.xml")); transformer.transform(source, result); // Output to console for testing StreamResult consoleResult =new StreamResult(System.out); transformer.transform(source, consoleResult); } catch (Exception e) { e.printStackTrace(); } }}
  • 12. OUTPUT will be <?xml version="1.0" encoding="UTF-8" standalone="no"?> <cars> <supercars company="Ferrari"> <carname type="formula one">Ferrari 101</carname> <carname type="sports">Ferrari 202</carname> </supercars> </cars> (you will have cars.xml created in C:>
  • 13. How to modify the xmldocument
  • 14. Original XML file(input.xml) <?xml version="1.0" encoding="UTF-8" standalone="no"?> <cars> <supercars company="Ferrari"> <carname type="formula one">Ferrari 101</carname> <carname type="sports">Ferrari 202</carname> </supercars> <luxurycars company="Benteley"> <carname>Benteley 1</carname> <carname>Benteley 2</carname> <carname>Benteley 3</carname> </luxurycars> </cars>
  • 15. import java.io.File; import javax.xml.parsers.*;I import javax.xml.transform.*; import org.w3c.dom.*; public class ModifyXmlFileDemo { public static void main(String argv[]) { try { File inputFile = new File("input.xml"); DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.parse(inputFile); Node cars = doc.getFirstChild(); Node supercar = doc.getElementsByTagName("supercars").item(0); // update supercar attribute NamedNodeMap attr = supercar.getAttributes(); Node nodeAttr = attr.getNamedItem("company"); nodeAttr.setTextContent("Lamborigini"); // loop the supercar child node NodeList list = supercar.getChildNodes();
  • 16. for (int temp = 0; temp < list.getLength(); temp++) { Node node = list.item(temp); if (node.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) node; if ("carname".equals(eElement.getNodeName())) { if("Ferrari 101".equals(eElement.getTextContent())) { eElement.setTextContent("Lamborigini 001"); } if("Ferrari 202".equals(eElement.getTextContent())) eElement.setTextContent("Lamborigini 002"); } } } NodeList childNodes = cars.getChildNodes(); for(int count = 0; count < childNodes.getLength(); count++) { Node node = childNodes.item(count); if("luxurycars".equals(node.getNodeName())) cars.removeChild(node); } // write the content on console
  • 17. TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); System.out.println("-----------Modified File-----------"); StreamResult consoleResult = new StreamResult(System.out); transformer.transform(source, consoleResult); } catch (Exception e) { e.printStackTrace(); } }}
  • 18. Output will be -----------Modified File----------- <?xml version="1.0" encoding="UTF-8" standalone="no"?> <cars> <supercars company="Lamborigini"> <carname type="formula one">Lamborigini 001</carname> <carname type="sports">Lamborigini 002</carname> </supercars> </cars>