JAXB小例子

package jaxb.test;

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;

@XmlRootElement
@XmlAccessorType(XmlAccessType.PROPERTY)
public class Account {
	private String id;
	private String name;

	@XmlAttribute (name = "id")
	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	@XmlElement(name = "name")
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

}

 

package jaxb.test;

import java.net.URL;

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

public class Client {
	public static void main(String[] args) throws Exception {
//		JAXBContext context = JAXBContext.newInstance(UserList.class);
		JAXBContext context = JAXBContext.newInstance(Account.class);
		Unmarshaller unmarshaller = context.createUnmarshaller();
		// URL xmlFileUrl = Client.class.getResource("users.xml");
		// UserList userList = (UserList) unmarshaller.unmarshal(xmlFileUrl);
		// System.out.println(userList.getUsers().get(0).getName());
		// System.out.println(userList.getUsers().get(0).getId());

		URL xmlFileUrl = Client.class.getResource("account.xml");
		Account account = (Account) unmarshaller.unmarshal(xmlFileUrl);
		System.out.println(account.getId());
		System.out.println(account.getName());
	}
}

 

package jaxb.test;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;

public class User {
	private int id;
    private String name;
 
    @XmlAttribute (name = "id")
    public int getId() {
        return id;
    }
 
    public void setId(int id) {
        this.id = id;
    }
 
    @XmlElement(name = "name")
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public String toString() {
        return id + ":" + name;
    }
}

 

package jaxb.test;

import java.util.List;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "users")
public class UserList {
    List<User> users;
 
    @XmlElement(name = "user")
    public List<User> getUsers() {
        return users;
    }
 
    public void setUsers(List<User> users) {
        this.users = users;
    }
}

 

<?xml version="1.0" encoding="UTF-8"?>
<account id="1">
	<name>ibm</name>
</account>

 

<?xml version="1.0" encoding="UTF-8"?>
<users xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
    <user id="1">
        <name>Unmi</name>
    </user>
    <user id="2">
        <name>She</name>
    </user>
</users>
 

你可能感兴趣的:(xml,.net,IBM)