In the work of manipulating XML in Java, the more convenient tool is JAXB (Java Architecture for XML Binding).
This tool makes it easy to generate XML tags and Java class correspondence. Refer to the information on the Internet for a brief explanation of some of the Java operations XML.
1. First define an XML schema file. Like what:
[HTML]View PlainCopyprint?
- <? XML version= "1.0" encoding="UTF-8" standalone="yes"?>
- <xs:schema version="1.0"
- xmlns:xs="Http://www.w3.org/2001/XMLSchema">
- <xs:element name="person">
- <xs:complextype>
- <xs:attribute name="name" type="xs:string"/>
- <xs:attribute name="age" type="Xs:int"/>
- </xs:complextype>
- </xs:element>
- </xs:schema>
The relevant XML schema definition rules can refer to http://www.w3.org/TR/xmlschema-2/
2. Generate the Java class.
Executing at the command line
C:\JAXB>XJC person.xsd
This generates the Persion class.
[Java]View PlainCopyprint?
- Package Com.test.xml
- Public class Person {
- protected String name;
- protected Integer age;
- Public String GetName () {
- return name;
- }
- public void SetName (String value) {
- this.name = value;
- }
- Public Integer Getage () {
- return age;
- }
- public void Setage (Integer value) {
- this.age = value;
- }
- }
The type of tag and the corresponding relationship of the Java type.
XML Schema Type |
Java Data Type |
Xsd:string |
Java.lang.String |
Xsd:integer |
Java.math.BigInteger |
Xsd:int |
Int |
Xsd.long |
Long |
Xsd:short |
Short |
Xsd:decimal |
Java.math.BigDecimal |
Xsd:float |
Float |
Xsd:double |
Double |
Xsd:boolean |
Boolean |
Xsd:byte |
Byte |
Xsd:qname |
Javax.xml.namespace.QName |
Xsd:datetime |
Javax.xml.datatype.XMLGregorianCalendar |
Xsd:base64binary |
Byte[] |
Xsd:hexbinary |
Byte[] |
Xsd:unsignedint |
Long |
Xsd:unsignedshort |
Int |
Xsd:unsignedbyte |
Short |
Xsd:time |
Javax.xml.datatype.XMLGregorianCalendar |
Xsd:date |
Javax.xml.datatype.XMLGregorianCalendar |
Xsd:g |
Javax.xml.datatype.XMLGregorianCalendar |
Xsd:anysimpletype |
Java.lang.Object |
Xsd:anysimpletype |
Java.lang.String |
Xsd:duration |
Javax.xml.datatype.Duration |
Xsd:notation |
Javax.xml.namespace.QName |
3. Read the contents of the XML to the Java object.
Java reads An example of the contents of XML.
[Java]View PlainCopy print?
- Public class Unmarshallerutil {
- Public Unmarshallerutil () {
- try {
- //1. Generating Jaxbcontex Objects
- Jaxbcontext context = jaxbcontext.newinstance ("Com.test.xml");
- //2. Generating Unmarsaller objects
- Unmarshaller Unmarshaller = Context.createunmarshaller ();
- File File = new file ("Artists.xml");
- //3. Unmarsaller
- Object obj = unmarshaller.unmarshal (file);
- Persons artists = (Persons) obj;
- //Other processing
- } catch (Jaxbexception ex) {
- }
- }
- public static void Main (string[] args) {
- new Unmarshallerutil ();
- }
- }
The JAXB tool for Java operation XML