package pero.common.Metied;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.MessageFormat;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
public class JaxbRootXml {
@SuppressWarnings("unchecked")
public static T readString(Class clazz,String context)throws JAXBException{
try{
JAXBContext jc=JAXBContext.newInstance(clazz);
Unmarshaller u=jc.createUnmarshaller();
return (T) u.unmarshal(new File(context));
}catch(JAXBException e){
throw e;
}
}
@SuppressWarnings("unchecked")
public static <T> T readConfig(Class<T> clazz, String config, Object... arguments) throws IOException,
JAXBException {
InputStream is = null;
try {
if (arguments.length > 0) {
config = MessageFormat.format(config, arguments);
}
JAXBContext jc = JAXBContext.newInstance(clazz);
Unmarshaller u = jc.createUnmarshaller();
is = new FileInputStream(config);
return (T) u.unmarshal(is);
} catch (IOException e) {
throw e;
} catch (JAXBException e) {
throw e;
} finally {
if (is != null) {
is.close();
}
}
}
@SuppressWarnings("unchecked")
public static <T> T readConfigFromStream(Class<T> clazz, InputStream dataStream) throws JAXBException {
try {
JAXBContext jc = JAXBContext.newInstance(clazz);
Unmarshaller u = jc.createUnmarshaller();
return (T) u.unmarshal(dataStream);
} catch (JAXBException e) {
throw e;
}
}
public static void main(String[] args) throws JAXBException {
TestRoot tr=JaxbRootXml.readString(TestRoot.class, "test/1.xml");
for(TestUser u:tr){
System.out.println(u.getId());
System.out.println(u.getName());
System.out.println(u.getPassword());
System.out.println(u.getAge());
}
}
}
package pero.common.Metied;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@SuppressWarnings("serial")
@XmlRootElement(name="Root")
public class TestRoot extends ArrayList{
@XmlElement(name = "user")
public List<TestUser> getUsers(){
return this;
}
}
package pero.common.Metied;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
@XmlAccessorType(XmlAccessType.FIELD)
public class TestUser {
@XmlAttribute(name = "id")
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@XmlAttribute(name = "name")
private String name;
@XmlAttribute(name = "password")
private String password;
@XmlAttribute(name = "age")
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
此处是要解析的
- user112320
- user245621
- user312321
- user412321