Java implementation XML file read and saved to object

Source: Internet
Author: User

Let's start by talking about four ways to parse XML:

1.DOM way: There are shortcomings but this shortcoming is also his merit. Here is a detailed description:

Organize nodes or pieces of information in a tree-shaped hierarchy to get multiple different data in the same document. Easy to use.

The advantage is that you can get multiple different data in the same document, which is easy to use.

The disadvantage is that the entire XML file needs to be loaded, which consumes some memory and resources, and if it is a small XML file you can try to parse it in the DOM way.

Tested when you read a file of size 10M in DOM mode, a memory overflow exception occurs.

2.SAX: Check the data while reading it, without parsing the entire document, so you don't need to store the data in memory. You can avoid memory overflow in DOM mode.

Pros: No need to consider excessive memory consumption when loading XML documents.

Cons: Coding when using sax parsers can be difficult, and it's difficult to access multiple different data in the same document at the same time.

3.DOM4J Way: dom4j performance is the best, even the sun JAXM is also used dom4j. Many of the current open source projects use dom4j, for example, the famous hibernate also uses dom4j to read XML configuration files. Consider the possible

The portability of dom4j is not good.

4.JDOM mode: The jdom itself does not contain parsers. It usually uses the SAX2 parser to parse and certify the input XML document

The following is a DOM implementation of the XML file read and translated into a Java class object:

Dom Mode:

XML File Code xmlpojo.xml:

<?xml version= "1.0" encoding= "UTF-8"?>
<items>
<item id= "328" >
<name>name1</name>
<size>23</size>
</item>
<item id= "303" >
<name>name2</name>
<size>22</size>
</item>
</items>

The Java class that corresponds to the XML file content:

public class xmlpojo{

String ID;

String name;

String size;

......

Setter and Getter Methods

}

XML reads the implementation class:

Import java.io.IOException;
Import Java.io.InputStream;
Import java.util.ArrayList;
Import java.util.List;
Import Javax.xml.parsers.DocumentBuilder;
Import Javax.xml.parsers.DocumentBuilderFactory;
Import javax.xml.parsers.ParserConfigurationException;
Import org.w3c.dom.Document;
Import org.w3c.dom.Element;
Import Org.w3c.dom.Node;
Import org.w3c.dom.NodeList;
Import org.xml.sax.SAXException;

public class Domtest {

public static void Main (string[] args) {
list<xmlpojo> list = new Domtest (). Parsexmlpojo ();
Prints the result of the read.
for (Xmlpojo p:list) {
SYSTEM.OUT.PRINTLN (P);
}

}

Parses the XML file and encapsulates the result into a collection of Xmlpojo to return
Private List<xmlpojo> Parsexmlpojo () {
List<xmlpojo> xmlpojolist = null;
try {
Get a DOM manufacturing facility
Documentbuilderfactory factory = Documentbuilderfactory
. newinstance ();
Get DOM Parser
Documentbuilder builder = Factory.newdocumentbuilder ();
Get an input stream of an XML file
InputStream instream = DomTest.class.getClassLoader ()
. getResourceAsStream ("Xmlpojo.xml");
Get the Document object through the parser
Document document = Builder.parse (instream);
Get all the item nodes to get, and get the content data for each item through each node.
NodeList list = document.getElementsByTagName ("item");
Xmlpojolist = new arraylist<xmlpojo> ();
Xmlpojo xmlpojo= null;
Traverse the person collection to encapsulate the data in the Xmlpojo object
for (int i = 0, size = list.getlength (); i < size; i++) {
Xmlpojo = new Xmlpojo ();
Get <person> knot points
Element e = (element) list.item (i);
Get its ID property
String id = e.getattribute ("id");
Xmlpojo.setid (integer.valueof (id));
Get all the child nodes of the current <person> node.
NodeList chilelist = E.getchildnodes ();
Traverse all child nodes to get the rest of the data.
for (int j = 0, CSize = Chilelist.getlength (); J < CSize; J + +) {
Node node = Chilelist.item (j);
Switch (Node.getnodename ()) {
Case "Name":
When the node is <name>, gets the content and assigns a value to the Xmlpojo.
String name = Node.gettextcontent ();
Xmlpojo.setname (name);
Break
Case "Size":
When the node is <age>, gets the content and assigns a value to the Xmlpojo.
String size = Node.gettextcontent ();
Xmlpojo.setsize (integer.valueof (size));
Break
}
}
Completes a <xmlPojo> node traversal, adding the Xmlpojo object to the collection.
Xmlpojolist.add (Xmlpojo);
Clears the data for the Xmlpojo object.
Xmlpojo = null;
}

} catch (Parserconfigurationexception e) {
E.printstacktrace ();
} catch (Saxexception e) {
E.printstacktrace ();
} catch (IOException e) {
E.printstacktrace ();
}
Returns the resulting data.
return xmlpojolist;
}
}

Java implementation XML file read and saved to object

Related Article

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.