標籤:mod ring hal return catch base64 class imp div
在java中操作XML的工作中中,比較方便的工具是JAXB(Java Architecture for XML Binding)。
利用這個工具很方便產生XML的tag和Java類的對應關係。參照網上的資料,簡單說明一下java操作xml的一些東西。
1.先定義一個XML Schema檔案。比如:
[html] view plain copy print?
- <?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>
相關XML Schema的定義規則可以參考http://www.w3.org/TR/xmlschema-2/
2.產生java類。
在命令列中執行
C:\jaxb>xjc person.xsd
這樣就產生了Persion類。
[java] view plain copy print?
- 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;
- }
- }
tag的類型和java的類型的對應關係。
| 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. 讀取xml的內容到java對象。
java讀取xml的內容的例子。
[java] view plain copy print?
- public class UnmarshallerUtil {
-
- public UnmarshallerUtil () {
- try {
- // 1. 產生JAXBContex對象
- JAXBContext context = JAXBContext.newInstance("com.test.xml");
-
- // 2. 產生Unmarsaller對象
- Unmarshaller unmarshaller = context.createUnmarshaller();
-
- File file = new File("artists.xml");
-
- // 3. Unmarsaller
- Object obj = unmarshaller.unmarshal(file);
- Persons artists = (Persons)obj;
-
- //其他處理
-
- } catch (JAXBException ex) {
-
- }
- }
-
- public static void main(String[] args) {
- new UnmarshallerUtil();
- }
- }
Java操作XML的JAXB工具