`

[Java]XML与JAXB

阅读更多
a.xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<customer id="cust id">
    <address>
        <street>jinjihulu</street>
        <city>suzhou</city>
        <zip>215200</zip>
    </address>
    <name>Marshall</name>
</customer>


a.xsd
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> 
   
    <xs:complexType name="Customer"> 
      <xs:sequence> 
         <xs:element name="address" type="Address"/> 
         <xs:element name="name" type="xs:string"/> 
      </xs:sequence> 
       <xs:attribute name="id" type="xs:string"/>       
    </xs:complexType> 
   
      <xs:complexType name="Address"> 
      <xs:sequence> 
         <xs:element name="street" type="xs:string"/> 
         <xs:element name="city" type="xs:string"/> 
         <xs:element name="zip" type="ZipCodeType"/> 
       </xs:sequence> 
   </xs:complexType> 
  
    <xs:simpleType name="ZipCodeType"> 
      <xs:restriction base="xs:integer"> 
         <xs:minInclusive value="10000"/> 
         <xs:maxInclusive value="99999"/> 
      </xs:restriction> 
    </xs:simpleType> 
    <xs:element name="customer" type="Customer"/> 
    <xs:element name="address" type="Address"/> 
</xs:schema> 



xjc生成java类
D:\JavaSoft\jdk6\bin>xjc -d f:/xmldemo -p demo.xml f:/xmldemo/a.xsd
parsing a schema...
compiling a schema...
demo\xml\Address.java
demo\xml\Customer.java
demo\xml\ObjectFactory.java

Customer.java
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> 
// Any modifications to this file will be lost upon recompilation of the source schema. 
// Generated on: 2011.12.30 at 04:13:13 PM CST 
//


package demo.xml;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;


/**
 * <p>Java class for Customer complex type.
 * 
 * <p>The following schema fragment specifies the expected content contained within this class.
 * 
 * <pre>
 * &lt;complexType name="Customer">
 *   &lt;complexContent>
 *     &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       &lt;sequence>
 *         &lt;element name="address" type="{}Address"/>
 *         &lt;element name="name" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *       &lt;/sequence>
 *       &lt;attribute name="id" type="{http://www.w3.org/2001/XMLSchema}string" />
 *     &lt;/restriction>
 *   &lt;/complexContent>
 * &lt;/complexType>
 * </pre>
 * 
 * 
 */
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Customer", propOrder = {
    "address",
    "name"
})
public class Customer {

    @XmlElement(required = true)
    protected Address address;
    @XmlElement(required = true)
    protected String name;
    @XmlAttribute
    protected String id;

    /**
     * Gets the value of the address property.
     * 
     * @return
     *     possible object is
     *     {@link Address }
     *     
     */
    public Address getAddress() {
        return address;
    }

    /**
     * Sets the value of the address property.
     * 
     * @param value
     *     allowed object is
     *     {@link Address }
     *     
     */
    public void setAddress(Address value) {
        this.address = value;
    }

    /**
     * Gets the value of the name property.
     * 
     * @return
     *     possible object is
     *     {@link String }
     *     
     */
    public String getName() {
        return name;
    }

    /**
     * Sets the value of the name property.
     * 
     * @param value
     *     allowed object is
     *     {@link String }
     *     
     */
    public void setName(String value) {
        this.name = value;
    }

    /**
     * Gets the value of the id property.
     * 
     * @return
     *     possible object is
     *     {@link String }
     *     
     */
    public String getId() {
        return id;
    }

    /**
     * Sets the value of the id property.
     * 
     * @param value
     *     allowed object is
     *     {@link String }
     *     
     */
    public void setId(String value) {
        this.id = value;
    }

}




Address.java
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> 
// Any modifications to this file will be lost upon recompilation of the source schema. 
// Generated on: 2011.12.30 at 04:13:13 PM CST 
//


package demo.xml;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;


/**
 * <p>Java class for Address complex type.
 * 
 * <p>The following schema fragment specifies the expected content contained within this class.
 * 
 * <pre>
 * &lt;complexType name="Address">
 *   &lt;complexContent>
 *     &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       &lt;sequence>
 *         &lt;element name="street" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *         &lt;element name="city" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *         &lt;element name="zip" type="{}ZipCodeType"/>
 *       &lt;/sequence>
 *     &lt;/restriction>
 *   &lt;/complexContent>
 * &lt;/complexType>
 * </pre>
 * 
 * 
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Address", propOrder = {
    "street",
    "city",
    "zip"
})
public class Address {

    @XmlElement(required = true)
    protected String street;
    @XmlElement(required = true)
    protected String city;
    protected int zip;

    /**
     * Gets the value of the street property.
     * 
     * @return
     *     possible object is
     *     {@link String }
     *     
     */
    public String getStreet() {
        return street;
    }

    /**
     * Sets the value of the street property.
     * 
     * @param value
     *     allowed object is
     *     {@link String }
     *     
     */
    public void setStreet(String value) {
        this.street = value;
    }

    /**
     * Gets the value of the city property.
     * 
     * @return
     *     possible object is
     *     {@link String }
     *     
     */
    public String getCity() {
        return city;
    }

    /**
     * Sets the value of the city property.
     * 
     * @param value
     *     allowed object is
     *     {@link String }
     *     
     */
    public void setCity(String value) {
        this.city = value;
    }

    /**
     * Gets the value of the zip property.
     * 
     */
    public int getZip() {
        return zip;
    }

    /**
     * Sets the value of the zip property.
     * 
     */
    public void setZip(int value) {
        this.zip = value;
    }

}




ObjectFactory.java
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> 
// Any modifications to this file will be lost upon recompilation of the source schema. 
// Generated on: 2011.12.30 at 04:13:13 PM CST 
//


package demo.xml;

import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlElementDecl;
import javax.xml.bind.annotation.XmlRegistry;
import javax.xml.namespace.QName;


/**
 * This object contains factory methods for each 
 * Java content interface and Java element interface 
 * generated in the generated package. 
 * <p>An ObjectFactory allows you to programatically 
 * construct new instances of the Java representation 
 * for XML content. The Java representation of XML 
 * content can consist of schema derived interfaces 
 * and classes representing the binding of schema 
 * type definitions, element declarations and model 
 * groups.  Factory methods for each of these are 
 * provided in this class.
 * 
 */
@XmlRegistry
public class ObjectFactory {

    private final static QName _Address_QNAME = new QName("", "address");
    private final static QName _Customer_QNAME = new QName("", "customer");

    /**
     * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: generated
     * 
     */
    public ObjectFactory() {
    }

    /**
     * Create an instance of {@link Customer }
     * 
     */
    public Customer createCustomer() {
        return new Customer();
    }

    /**
     * Create an instance of {@link Address }
     * 
     */
    public Address createAddress() {
        return new Address();
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link Address }{@code >}}
     * 
     */
    @XmlElementDecl(namespace = "", name = "address")
    public JAXBElement<Address> createAddress(Address value) {
        return new JAXBElement<Address>(_Address_QNAME, Address.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link Customer }{@code >}}
     * 
     */
    @XmlElementDecl(namespace = "", name = "customer")
    public JAXBElement<Customer> createCustomer(Customer value) {
        return new JAXBElement<Customer>(_Customer_QNAME, Customer.class, null, value);
    }

}



JaxbDemo.java
package demo.xml;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class JaxbDemo {
	
	public static void main(String[] args) throws Exception {
		unmarshalling();
		marshalling();
	}
	
	static void unmarshalling() throws Exception{
		JAXBContext jc = JAXBContext.newInstance("demo.xml"); 
        Unmarshaller u = jc.createUnmarshaller(); 
        JAXBElement customerE = (JAXBElement) u.unmarshal(new FileInputStream( 
                                "F:\\xmldemo\\a.xml")); 
        Customer bo = (Customer) customerE.getValue(); 
        System.out.println(bo.getName() + " : " + bo.getAddress().getCity() + " : " + bo.getId());
	}
	
	static void marshalling()throws Exception{
		JAXBContext jc = JAXBContext.newInstance(Customer.class); 
		Marshaller ms = jc.createMarshaller();
		ms.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
		
		Customer cust = new Customer();
		cust.setId("cust id");
		cust.setName("Marshall");
		Address a = new Address();
		a.setCity("suzhou");
		a.setStreet("jinjihulu");
		a.setZip(215200);
		cust.setAddress(a);
		
		OutputStream os = new FileOutputStream("F:\\xmldemo\\a.xml");
		ms.marshal(cust, os);
		os.close();
	}

}



分享到:
评论

相关推荐

    JAXB工具类 xml转为java对象 java对象转为xml

    Java Architecture for XML Binding (JAXB) 是Java平台中用于处理XML和Java对象之间转换的一个标准API。它使得在Java应用程序中使用...在实际项目中,结合JAXB与XML Schema,可以构建更健壮、易于维护的数据交换系统。

    通过JAXB实现完成java对象和xml的互相转换

    在本文中,我们将深入探讨如何使用JAXB实现Java对象与XML的互相转换。 首先,我们需要理解JAXB的基本工作原理。JAXB基于Java注解,这些注解用于标记Java类和它们的属性,以便JAXB知道哪些元素和属性应该映射到XML中...

    JAVA JAXB 解析XML嵌套子节点为字符串

    在Java开发中,JAXB(Java Architecture for XML Binding)是一个标准的API,用于将XML文档与Java对象之间进行互相转换。这个技术对于处理XML数据,尤其是解析和生成XML文档非常有用。当我们面临XML文档中存在嵌套子...

    JAXB技术实现xml与java对象互相转化代码教程

    使用java jdk的JAXB技术实现xml与java对象互相转化代码教程: JDK中JAXB相关的重要Class和Interface:(来源于百度百科JAXB) •JAXBContext类,是应用的入口,用于管理XML/Java绑定信息。 •Marshaller接口,将Java...

    利用JAXB进行xml和javabean之间转换

    在Java世界中,XML(可扩展标记语言)作为一种数据交换格式,被广泛用于存储和传输数据。...在实际项目中,可以结合标签中的“源码”和“工具”概念,进一步探索JAXB与其他框架或库的集成,提升开发体验。

    Java XML绑定技术 (Castor JAXB XMLBeans)

    JAXB(Java Architecture for XML Binding)是Sun Microsystems(现已被Oracle收购)推出的一种Java XML绑定框架。它是Java EE标准的一部分,提供了一种机制来将Java对象与XML文档相互转换。使用JAXB,可以通过简单...

    java 使用 JAXB 将xml转换为 bean 包含xml和dto和读取文件的util类

    总结来说,这个压缩包提供的内容涉及了Java中使用JAXB进行XML与Java对象之间转换的实际应用,以及辅助的DTO和文件读取工具。这些对于理解和实现XML数据处理的Java应用非常有帮助。开发者可以通过学习和使用这些示例...

    JAXB_Java Architecture For XML Binding

    JAXB与RESTful服务** 在Java EE环境中,JAXB常与JAX-RS一起使用,实现RESTful Web服务的数据交换。JAXB可以自动将Java对象转换为JSON或XML响应,简化了服务器端的开发。 **6. JAXB优化** 为了提高性能,可以使用...

    jaxb (XML操作)

    **JAXB(Java Architecture for XML Binding)** 是Java平台中用于处理XML的一种强大的工具,它提供了将XML文档与Java对象之间的映射,从而方便XML数据的解析和生成。通过JAXB,开发者可以轻松地实现XML数据到Java...

    JAXB 利用xsd文件生成java类

    5. **JAXB与Maven/Gradle集成**: - Maven可以通过`maven-jaxb2-plugin`或`jaxb2-maven-plugin`插件实现XSD到Java的编译。 - Gradle则可以使用`jaxb`插件或自定义Task来执行相同的操作。 6. **使用示例**: - ...

    JAXB xml与对象转换

    1. **创建Java类**:首先,你需要创建与XML结构对应的Java类。可以手动编写,也可以使用XSD文件生成Java类,如使用`xjc`命令或IDE工具。 2. **添加注解**:在Java类和字段上添加JAXB注解,这些注解告诉JAXB如何映射...

    java学习之jaxb的学习一

    五、JAXB与XML Schema XML Schema是一种用于定义XML文档结构的规范。JAXB允许将XML Schema直接映射到Java类,生成对应的Java模型。这样,我们就可以根据XML Schema自动创建Java类,简化开发工作。 六、JAXB与Maven...

    JAXB与xml相互转换实例

    理解并熟练使用JAXB,能够极大地提高开发效率并减少错误,使得Java应用与XML数据的交互变得更加简单和高效。在实际工作中,开发者可以根据项目需求和团队习惯选择是否采用JAXB,或者考虑其他替代方案,如DOM、SAX、...

    jaxb生成XML例子

    JAXB (Java Architecture for XML Binding) 是 Java 中用于对象到XML以及XML到对象转换的API。它使得开发者能够轻松地将Java对象模型映射到XML文档,并反之亦然。在给定的例子中,我们将深入理解如何使用JAXB注解来...

    java 解析XML性能对比分析Demo

    JAXB主要用于XML到Java对象的自动绑定,以及Java对象到XML的转换。它适用于数据绑定场景,可以轻松地将XML数据映射为Java对象,简化了序列化和反序列化的流程,但在大量XML数据的处理上,性能可能不如DOM4J和SAX。 ...

    jaxb解析xml

    2. 使用 JAXB 的 XJC 工具,通过定义 schema 的方式实现 Java 对象与 XML 的绑定。 ### 3.2 JAXB Annotation 使用说明 #### 3.2.1 @XmlType @XmlType 定义映射的一些规则,用在 class 类的注解,常与 @...

    webservice之使用jaxb把xml转换Object或把对象转换成xml文件

    JAXB与其他XML处理技术(如DOM、SAX、StAX)相比,更注重于对象模型与XML之间的绑定,适用于需要频繁进行对象与XML转换的场景。而DOM适合处理小规模的XML文档,SAX和StAX则适用于大文件流式处理。 总结,JAXB是Java...

    JAXB的 eclipse插件

    总结一下,JAXB的Eclipse插件是Java开发者处理XML数据的强大工具,它集成了XML Schema与Java类的相互转换、源代码编辑支持以及调试等功能。通过利用这些插件,开发者可以更加高效地进行XML相关的开发工作,实现Java...

    JAXB XMLSPY

    JAXB的核心在于将Java类与XML Schema(XSD)进行绑定。通过这种方式,Java对象可以直接序列化为XML文档,或者从XML文档反序列化为Java对象。这个过程是自动化的,无需编写大量的转换代码。JAXB提供了两个主要的过程...

Global site tag (gtag.js) - Google Analytics