Three ways to parse XML in Java

Source: Internet
Author: User
Tags gettext

Three ways to parse XML in Java

1.SAX Event Parsing

Package Com.wzh.sax;import Org.xml.sax.attributes;import Org.xml.sax.saxexception;import Org.xml.sax.helpers.defaulthandler;//public class Saxhandler extends DefaultHandler {@Overridepublic void Startdocument () throws Saxexception {System.out.println ("Start parsing XML Document ...");} @Overridepublic void Enddocument () throws Saxexception {System.out.println ("End parsing XML Document ...");} @Overridepublic void Startelement (String uri, String localname, String Qname,attributes Attributes) throws Saxexception { TODO auto-generated Method Stubsuper.startelement (URI, LocalName, qName, attributes); System.out.println ("Start parsing node [" +qname+ "] ..."); SYSTEM.OUT.PRINTLN ("Common [" +attributes.getlength () + "] Properties");} @Overridepublic void characters (char[] ch, int start, int length) throws Saxexception {//TODO auto-generated method Stubsu Per.characters (CH, start, length); String content =new string (ch,start,length); SYSTEM.OUT.PRINTLN (content);} @Overridepublic void EndElement (String uri, String localname, String qName) throws Saxexception {//TODO auto-generated Method Stubsuper.endelement (URI, LocalName, QName); SYSTEM.OUT.PRINTLN ("End Parsing XML node ...");}}

  

2.Dom Load parsing

Package Com.wzh.dom;import Java.util.iterator;import Javax.xml.parsers.documentbuilder;import Javax.xml.parsers.documentbuilderfactory;import Org.w3c.dom.document;import Org.w3c.dom.element;import Org.w3c.dom.namednodemap;import Org.w3c.dom.node;import Org.w3c.dom.nodelist;public class DomHandler {/* * Parse XML */ public void Read (String fileName) throws Exception {//Define factory API enables applications to obtain a parser that generates a DOM object tree from an XML document Documentbuilderfactory Factory = Documentbuilderfactory.newinstance ();//After obtaining an instance of this class, you will be able to parse Xmldocumentbuilder builder from various input sources = Factory.newdocumentbuilder ();//Builder.parse (This.getclass (). getResourceAsStream ("/" + fileName);// The document interface represents the entire HTML or XML documentation, conceptually, it is the root of the document tree and provides a basic access to the document data File = Builder.parse (This.getclass (). getResourceAsStream ("/" + fileName);//Get root node element root = Document.getdocumentelement (); System.out.println (Root.getnodename ());//Read the database node NodeList interface provides an abstraction of the ordered set of nodes nodeList nodeList = Root.getelementsbytagname ("database"); for (int i = 0; i < nodelist.getlength (); i++) {//Get a node nodes = Nodelist.item (i);//Get all the properties of the node NamedNodeMap attributes = Node.getattributes (); for (int j = 0; J &lt ; Attributes.getlength (); J + +) {Node attribute = Attributes.item (j); System.out.println (Attribute.getnodename () + ":" + attribute.getnodevalue ()); Get all child node Data nodelist childnodes=node.getchildnodes (); for (int j = 0; J < Childnodes.getlength (), j + +) {node childnode=c Hildnodes.item (j); System.out.println (Childnode.getnodename () + ":" +childnode.getnodevalue ());}}} public static void Main (string[] args) throws Exception {new Domhandler (). Read ("Data-source.xml");}}

  

3.DOM4J parsing

Package com.wzh.dom4j;

Import Java.io.FileOutputStream;
Import Java.sql.DatabaseMetaData;
Import Java.util.Iterator;
Import java.util.List;

Import org.dom4j.*;
Import Org.dom4j.io.OutputFormat;
Import Org.dom4j.io.SAXReader;
Import Org.dom4j.io.XMLWriter;

public class Dom4jhandler {

public void Add () throws Exception {
//1. Create a document
Document document = Documenthelper.createdocument ();
2. Add data to document
Element root = Document.addelement ("DataSource");
Add a comment
Root.addcomment ("This is a comment message");
Add a child node under the root root node
Element database = root.addelement ("database");
Database.addattribute ("name", "MySQL");
Database.addattribute ("version", "5.0");
//Add child nodes
Database.addelement ("Driver"). SetText ("Com.mysql.jdbc.Driver");
Database.addelement ("url")
. SetText ("Jdbc:mysql://localhost:3306/myjdbc");
Database.addelement ("User"). SetText ("root");
Database.addelement ("password"). SetText ("root");
//3. Write document out of file
OutputFormat format = Outputformat.createprettyprint ();
Format.setencoding ("Utf-8");
///FileOutputStream the path generated by default at the root path
XMLWriter XW = new XMLWriter (New FileOutputStream ("Db.xml"), format);
Xw.write (document);
Xw.close ();
}

public void Update (String fileName) throws Exception {
SAX parser
Saxreader Saxreader = new Saxreader ();
Read the Object
Document document = Saxreader.read (This.getclass (). getResourceAsStream (
"/" + fileName);
Element root = Document.getrootelement ();
list<element> Databases_node = root.elements ("database");
for (Element Database_node:databases_node) {
if (Database_node.attributevalue ("name"). Equalsignorecase ("MySQL")) {
System.out.println ("Old:"
+ database_node.attributevalue ("name"));
Database_node.attribute ("name"). SetText ("Oracle");
System.out.println ("Update:"
+ database_node.attributevalue ("name"));

Database_node.element ("Driver"). SetText ("Oracel");
Database_node.element ("url"). SetText ("jdbc");

Delete Password node
Database_node.remove (database_node.element ("password"));

Delete Property
Database_node.remove (Database_node.attribute ("version"));
}
}

OutputFormat format = Outputformat.createprettyprint ();
Format.setencoding ("Utf-8");
FileOutputStream the default generated path in the root path
XMLWriter XW = new XMLWriter (New FileOutputStream ("Db2.xml"), format);
Xw.write (document);
Xw.close ();
}

public void Read (String fileName) throws Exception {
SAX parser
Saxreader Saxreader = new Saxreader ();
Read the Object
Document document = Saxreader.read (This.getclass (). getResourceAsStream (
"/" + fileName);
Element root = Document.getrootelement ();
SYSTEM.OUT.PRINTLN ("root node:" + Root.getname ());

//List<element> childelements=root.elements ();
List<element> childelements = root.elements ("database");
for (Element child:childelements) {
//Get property does not know property name when traversing method
List<attribute> attributes = Child.attributes ();
//For (Attribute attribute:attributes) {
//System.out.println (Attribute.getname () + ":" +attribute.getvalue () );
//}
String name = Child.attributevalue ("name");
//String Version = Child.attributevalue ("version");
String Version = Child.attribute ("version"). GetValue ();
System.out.println (name + ":" + version);

Get child nodes
List<element> childs=child.elements ();
for (Element element:childs) {
System.out.println (Element.getname () + ":" +element.gettext ());
// }
System.out.println (Child.elementtext ("Driver"));
System.out.println (child.element ("url"). GetText ());
System.out.println (Child.elementtexttrim ("user"));
System.out.println (child.element ("password"). Gettexttrim ());

}
}

public static void Main (string[] args) throws Exception {
New Dom4jhandler (). Read ("Data-source.xml");
New Dom4jhandler (). Add ();
New Dom4jhandler (). Update ("Data-source.xml");
}
}

Three ways to parse XML in Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.