際際滷

際際滷Share 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

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>