In programming, it is reasonable and necessary to destroy an object after the execution of the program is finished. However, it is inevitable that sometimes we want to persist objects so that we can restore them directly next time without having to assign values to the objects again. Then there is the problem of object serialization. The serialization of this object allows us to transmit the correct transmission of the object data on different platforms, but this serialization is limited, only for Java solutions that must be the same as Java programs to parse. To pursue more general scenarios, we can transform data into XML format for more general solutions. In other words, XML is cross-platform and Cross-language.
One, what is XML.
Extensible Markup Language is a markup language that is used to mark electronic files so that they are structured. Ideal for World Wide Web transmissions, providing a unified approach to describing and exchanging structured data that is independent of applications or vendors.
XML support in JavaThe Javax.xml.* class library that is published with the JDK. XOM Open Source Library, this looks more intuitive and easy to learn, so here we use XOM to provide support. Open Source Library Address: www.xom.nu, interested and energetic can follow the tutorials provided above to learn, or very easy to start.
the practical classes and methods in XomElement: As the name implies, the elements that represent XML, both the root element and the child element, are represented by it, and the related methods are: Getchildelements (), with multiple overloaded methods for obtaining all the child elements below the current element, and returning the elements object. Getfirstchildelement (), which also has multiple overloaded versions, cannot be misled by the naming of this method, which is used to get a single element object (in contrast to the previous method), not just the first child element object. AppendChild (), which is used to add a self element to the current element. AddAttribute () to add attributes to the element. A list of Elements:element objects, but not really in Java list, with Get () and size () methods. Document: Generally, the root element can be passed as a parameter to construct a Document object, which can actually be understood as encapsulating an XML element and constructing an XML "document" object. There is a ToXml () method that can be really converted to XML-formatted data (the previous operation is equivalent to just a logical construct of XML). But below we will see that this method does not produce the well-formed XML document we want. You need to make formatting adjustments with the help of the serializer class. Getrootelement () gets the root element. Serializer: Used to "format" XML to make the output more readable, commonly used methods are: SetIndent (), Set line Indent setmaxlength (), set the maximum length of the row, this length is not fixed dead, When the length of an element name is longer than the length of the set, the length of the set is not limited to the display of the element name. Write (), passes in the Document object to be formatted, and generates the XML output in the format that we set through the above method. Serializer (): constructor, you can pass in the "formatted" output stream, you can also set the encoding method, the default encoding is UTF8 encoding. Builder: This class is used to recover data from the XML format, passing the build () method to the XML data source and returning a Document object. This allows us to recover data from the Document object. Attribute: Represents the parameters of an element. (This article does not detail this class)
Four, xom actual combat 1. Download and import jar package, this relatively simple, it is not elaborated, you can search the Baidu tutorial 2. Convert data to XML format (write)The first is a student class, where an instance of this class will act as a child element of XML, as follows:
public class Student {
private String firstName;
Private String lastName;
Public Student () {
} public
Student (string firstName, String lastName) {
super ();
This.firstname = FirstName;
This.lastname = LastName;
}
Converts the student object to an XML child element located under root
GetXML () {
element student = new Element ("student");
Element-i = new Element ("a");
First.appendchild (firstName);
Student.appendchild (a);
Element last = new Element (' last ');
Last.appendchild (lastName);
Student.appendchild (last);
return student
}
}
The code in the main class is as follows:
public class Main {public
static void Main (String args[]) {
list<student> students = new Arraylist<stude Nt> ();
Students.add (New Student ("Dr.bunsen", "Honeydew"));
Students.add (New Student ("Gonzo", "The Great"));
Students.add (New Student ("Phillip J.", "Fry"));
Students.add (New Student ("Ming", "King"));
Students.add (New Student ("Red", "Lin"));
Put student data one by one in the list into the root directory root
= element root = new Element ("Students");
for (Student student:students) {
root.appendchild (Student.getxml ());
}
Construct XML Document Object document
= new document (root);
System.out.println (Document.toxml ());
}
Output the results to the console, we found that ToXML () does not have any format, just, as follows: (part of the screenshot)
Let's use serializer to "format" the XML: Add the method Format () to main class main, and call it in the main () method, and the format () method is as follows:
<span style= "FONT-SIZE:14PX;" >/**
* Document XML "format" *
@param Document object that needs to be formatted
* @throws IOException * *
The public
static void format (document document) throws IOException {
Serializer serializer = new Serializer (System. Out, "GBK");
Set Line Indent
serializer.setindent (4);
Set the maximum length of the row
(serializer.setmaxlength);
Serializer.write (document);
} </span>
The output is as follows, and you can see that it is actually more readable than the output above.
Of course, we found that the above operation is simply to output XML data to the console, of course, we often need to store it as a file, this is also easy to do, modify the format () method signature, format (Outputsteam os,document doc) , the incoming output stream allows us to have greater flexibility. Call the format () function again in the main function:
<span style= "FONT-SIZE:14PX;" >format (New Bufferedoutputstream (
new FileOutputStream ("Students.xml")), document);</span>
You can find the XML file in the appropriate directory and use Notepad to open the view below and verify correctly.
3. Restore data from XML format (read)Add the ToString () method for the student class. Then add the method Recovery () to the main class and call it in the main () function, pass in the file path and parse the code as follows:
<span style= "FONT-SIZE:14PX;" >/**
* Data recovery of the specified XML file * *
@param fileName
* @throws Exception
/
private static list< student> recovery (String fileName) throws Exception {
list<student> students = new Arraylist<student > ();
Document document = new Builder (). Build (New File (FileName));
Elements Elements = Document.getrootelement (). getchildelements ();
for (int i = 0; i < elements.size (); i++) {
element element = Elements.get (i);
Student Student = new Student (Element.getfirstchildelement ("a")
. GetValue (), Element.getfirstchildelement ( "Last")
. GetValue ());
Students.add (student);
}
return students;
} </span>
The output is as follows, read out successfully.
Here's a trap, refer to the XOM official tutorial, that's what it says.
Depending on platform, relative URL may or may is interpreted as file names. On Windows they seem. On Unix/linux, they are. It is very safer to use full, unrelative file URLs such as File:///home/elharo/Projects/data/example.xml which should work On essentially any platform. Alternately, can pass a Java.io.File object to the build method instead of a URL.
The general meaning is that the URL we passed in could not be recognized as a correct file path, which would cause our program to try to access the network to get the XML file and thus produce an exception, so what we need to do is to pass filename to the file object as above, Force specifies that this is a file object. If the line is reversed, the build () method call is changed to
Document document = new Builder (). Build (FileName);
An exception can occur:
v. Summary:We can see that the XOM Open Source Library does provide us with a lot of convenience, but it offers far more than that. For example, you can also use attribute to set the parameters of an element, and so on. Specific reference to the official website of the tutorial.