Example code for generating and parsing XML files and strings in Java

Source: Internet
Author: User
This article mainly introduces the example code for Java to generate and parse XML files and strings. For more information, see section 1. basic knowledge:
Java parses XML in four ways: DOM, SAX, JDOM, and DOM4J.

2. Introduction
1) DOM
(1) Introduction

The interface provided by W3C (org. w3c. dom) reads the entire XML file into the memory and constructs a DOM tree to operate on each Node. The advantage is that the entire document is always in the memory. we can access any node at any time and we are familiar with tree traversal. The disadvantage is that memory consumption, you must wait until all documents are read into the memory for processing.

(2) sample code:

 
     
          
               
    
     599
                
    
     CMCC
            
           
               
    
     699
                
    
     ChinaNet
            
       
  
 
import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.StringReader;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.parsers.ParserConfigurationException;import javax.xml.transform.Transformer;import javax.xml.transform.TransformerConfigurationException;import javax.xml.transform.TransformerException;import javax.xml.transform.TransformerFactory;import javax.xml.transform.dom.DOMSource;import javax.xml.transform.stream.StreamResult;import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.Node;import org.w3c.dom.NodeList;import org.xml.sax.InputSource;import org.xml.sax.SAXException;public class XMLHandler {    public XMLHandler(){            }        public String createXML(){        String xmlStr = null;        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();        try {            DocumentBuilder builder = factory.newDocumentBuilder();            Document document = builder.newDocument();            document.setXmlVersion("1.0");                        Element root = document.createElement("root");            document.appendChild(root);                        Element telephone = document.createElement("TelePhone");                        Element nokia = document.createElement("type");            nokia.setAttribute("name", "nokia");                        Element priceNokia = document.createElement("price");            priceNokia.setTextContent("599");            nokia.appendChild(priceNokia);                        Element operatorNokia = document.createElement("operator");            operatorNokia.setTextContent("CMCC");            nokia.appendChild(operatorNokia);                        telephone.appendChild(nokia);                        Element xiaomi = document.createElement("type");            xiaomi.setAttribute("name", "xiaomi");                        Element priceXiaoMi = document.createElement("price");            priceXiaoMi.setTextContent("699");            xiaomi.appendChild(priceXiaoMi);                        Element operatorXiaoMi = document.createElement("operator");            operatorXiaoMi.setTextContent("ChinaNet");            xiaomi.appendChild(operatorXiaoMi);                        telephone.appendChild(xiaomi);                        root.appendChild(telephone);                        TransformerFactory transFactory = TransformerFactory.newInstance();            Transformer transFormer = transFactory.newTransformer();            DOMSource domSource = new DOMSource(document);                        //export string            ByteArrayOutputStream bos = new ByteArrayOutputStream();            transFormer.transform(domSource, new StreamResult(bos));            xmlStr = bos.toString();                        //-------            //save as file            File file = new File("TelePhone.xml");            if(!file.exists()){                file.createNewFile();            }            FileOutputStream out = new FileOutputStream(file);            StreamResult xmlResult = new StreamResult(out);            transFormer.transform(domSource, xmlResult);            //--------        } catch (ParserConfigurationException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }catch (TransformerConfigurationException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }catch (TransformerException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }                return xmlStr;    }        public void parserXML(String strXML){        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();        try {            DocumentBuilder builder = factory.newDocumentBuilder();            StringReader sr = new StringReader(strXML);            InputSource is = new InputSource(sr);            Document doc = builder.parse(is);            Element rootElement = doc.getDocumentElement();            NodeList phones = rootElement.getElementsByTagName("type");            for (int i = 0; i < phones.getLength(); i++) {                Node type = phones.item(i);                String phoneName = ((Element)type).getAttribute("name");                System.out.println("Phone name = "+phoneName);                NodeList properties = type.getChildNodes();                for (int j = 0; j < properties.getLength(); j++) {                    Node property = properties.item(j);                    String nodeName = property.getNodeName();                    if (nodeName.equals("price")) {                        String price=property.getFirstChild().getNodeValue();                        System.out.println("price="+price);                    } else if (nodeName.equals("operator")) {                        String operator=property.getFirstChild().getNodeValue();                        System.out.println("operator="+operator);                    }                }            }        } catch (ParserConfigurationException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }catch (SAXException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }        public static void main(String[] args) {        XMLHandler handler = new XMLHandler();        String xml = handler.createXML();        System.out.println(xml);        handler.parserXML(xml);    }}

(3) differences between elements and nodes (org. w3c. dom)
The Node object is the main data type of the entire Document Object Model. it is the most basic object in DOM and represents the abstract Node in the document tree. However, in actual use, the Node object is rarely used directly, but the sub-object Element, Attr, and Text of the Node object are used.
An Element object represents an Element in an HTML or XML document. it is the primary sub-object of the Node class and can contain attributes. Therefore, an Element has a method to access its attributes.
Element is inherited from Node. an Element is defined in a small scope and must be a Node containing complete information. for example

...

. However, a node is not necessarily an element, but an element must be a node.
Node has several sub-types: Element, Text, Attribute, RootElement, Comment, and Namespace.

2). SAX


3). JDOM

4). DOM4J
(1) Introduction
Dom4j is currently the best in xml parsing (Hibernate and Sun's JAXM also use dom4j to parse XML), which combines many functions beyond the representation of basic XML documents, including integrated XPath support, XML Schema support, and event-based processing for large or streaming documents.
Add jaxen. jar when using XPATH; otherwise, the following error occurs:

Exception in thread "main" java.lang.NoClassDefFoundError: org/jaxen/JaxenExceptionat org.dom4j.DocumentFactory.createXPath(DocumentFactory.java:230)at org.dom4j.tree.AbstractNode.createXPath(AbstractNode.java:207)      at org.dom4j.tree.AbstractNode.selectNodes(AbstractNode.java:164)

(2) sample code:

Import java. io. file; import java. io. fileWriter; import java. io. IOException; import java. io. stringReader; import java. io. stringWriter; import java. util. list; import org. dom4j. document; import org. dom4j. extends entexception; import org. dom4j. export enthelper; import org. dom4j. element; import org. dom4j. io. outputFormat; import org. dom4j. io. SAXReader; import org. dom4j. io. XMLWriter; import org. xml. sax. inputSource; public class XMLHandler {public XMLHandler () {// TODO Auto-generated constructor stub} public String createXML () {String strXML = null; Document document = incluenthelper. createDocument (); Element root = document. addElement ("root"); Element phone = root. addElement ("TelePhone"); Element nokia = phone. addElement ("type"); nokia. addAttribute ("name", "nokia"); Element price_nokia = nokia. addElement ("price"); price_nokia.addText ("599"); Element operator_nokia = nokia. addElement ("operator"); operator_nokia.addText ("CMCC"); Element xiaomi = phone. addElement ("type"); xiaomi. addAttribute ("name", "xiaomi"); Element price_xiaomi = xiaomi. addElement ("price"); price_xiaomi.addText ("699"); Element operator_xiaomi = xiaomi. addElement ("operator"); operator_xiaomi.addText ("ChinaNet"); // -------- StringWriter strWtr = new StringWriter (); OutputFormat format = OutputFormat. createPrettyPrint (); format. setEncoding ("UTF-8"); XMLWriter xmlWriter = new XMLWriter (strWtr, format); try {xmlWriter. write (document);} catch (IOException e1) {// TODO Auto-generated catch block e1.printStackTrace ();} strXML = strWtr. toString (); // -------- // ------- // strXML = document. asXML (); // ------ // ------------- File file = new File ("TelePhone. xml "); if (file. exists () {file. delete ();} try {file. createNewFile (); XMLWriter out = new XMLWriter (new FileWriter (file); out. write (document); out. flush (); out. close ();} catch (IOException e) {// TODO Auto-generated catch block e. printStackTrace ();} // -------------- return strXML;} public void parserXML (String strXML) {SAXReader reader = new SAXReader (); StringReader sr = new StringReader (strXML ); inputSource is = new InputSource (sr); try {Document document = reader. read (is); Element root = document. getRootElement (); // get element List
 
  
PhoneList = root. elements ("TelePhone"); List
  
   
TypeList = phoneList. get (0). elements ("type"); for (int I = 0; I
   
    

5) XPATH
(1) Introduction
XPath is a language used to search for information in XML documents. XPath is used to navigate through elements and attributes in XML documents.
Detailed syntax introduction reference: http://w3school.com.cn/xpath/index.asp

(2) sample code:

import java.io.IOException;import java.io.StringReader;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.parsers.ParserConfigurationException;import javax.xml.xpath.XPath;import javax.xml.xpath.XPathConstants;import javax.xml.xpath.XPathExpression;import javax.xml.xpath.XPathExpressionException;import javax.xml.xpath.XPathFactory;import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.Node;import org.w3c.dom.NodeList;import org.xml.sax.InputSource;import org.xml.sax.SAXException;public class XMLHandler {    public XMLHandler() {        // TODO Auto-generated constructor stub    }        public void parserXML(String strXML){        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();        try {            DocumentBuilder builder = factory.newDocumentBuilder();            StringReader sr = new StringReader(strXML);            InputSource is = new InputSource(sr);            Document doc = builder.parse(is);                        XPathFactory xFactory = XPathFactory.newInstance();            XPath xpath = xFactory.newXPath();            XPathExpression expr = xpath.compile("/root/TelePhone/type");            NodeList phones = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);              for (int i = 0; i < phones.getLength(); i++) {                Node type = phones.item(i);                String phoneName = ((Element)type).getAttribute("name");                System.out.println("Phone name = "+phoneName);                XPathExpression expr1 = xpath.compile("./*");                NodeList list = (NodeList) expr1.evaluate(type, XPathConstants.NODESET);                for(int j =0;j
     
      "+                    "
      
       "+                        "
       
        "+                            "
        
         "+                                "
         
          599
         "+                                "
         
          CMCC
         "+                            "
        "+                            "
        
         "+                                "
         
          699
         "+                                "
         
          ChinaNet
         "+                            "
        "+                        "
       "+                    "
      ";        XMLHandler handler = new XMLHandler();        handler.parserXML(strXML);    }}
     

For more articles about the instance code used to generate and parse XML files and strings in Java, please follow the PHP Chinese website!

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.