java解析xml
<?xml version="1.0" encoding="UTF-8"?> <mimetype> <default> <mime-type>text/html</mime-type> </default> <mime-mapping> <extension>zip</extension> <mime-type>application/zip</mime-type> </mime-mapping> <mime-mapping> <extension>xml</extension> <mime-type>text/xml</mime-type> </mime-mapping> </mimetype>
1. SAXReader
public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException, DocumentException { //流式读取 File file = new File("mimetype.xml"); Document doc = new SAXReader().read(file); Element mimetype = doc.getRootElement(); System.out.println("根元素名:" + mimetype.getName()); Element defaultElement = mimetype.element("default"); System.out.println("默认元素的mime-type:" + defaultElement.elementText("mime-type")); List<Element> mime_mappings = mimetype.elements("mime-mapping"); System.out.println("元素集合的数据:" + mime_mappings.size()); }
这是读文件的,好像直接读字符串还不怎么方便。
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><mimetype></mimetype>"; Reader reader = new StringReader(xml); Document doc = new SAXReader().read(reader);
以Reader为桥梁来读取String类型的xml 2016-03-12 13:00:27
2. JAXB
@XmlRootElement(name="user") public class User { public String name = "ken"; public int age = 24; public static void main(String[] args) throws Exception { JAXBContext jaxbContext = JAXBContext.newInstance(User.class); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); User m = new User(); jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); //有缩进 jaxbMarshaller.marshal(m, System.out); String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><user><name>ken</name><age>24</age></user>"; Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); User m2 = (User) unmarshaller.unmarshal(new StringReader(xml)); System.out.println("我的名字:" + m2.name); } }
简单类型的解析与序列化 2016-03-12 17:48:55
@XmlRootElement(name="user") public class User { public String name = "ken"; public int age = 24; public Address address = new Address(); public static class Address{ public String name = "永州"; } }
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<user>
<name>ken</name>
<age>24</age>
<address>
<name>永州</name>
</address>
</user>
@XmlRootElement(name="user") public class User { public String name = "ken"; public int age = 24; @XmlElementWrapper(name="list") public List<Address> address; public static class Address{ public String name = "永州"; public Address(String name){ this.name = name; } } }
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<user>
<name>ken</name>
<age>24</age>
<list>
<address>
<name>永州</name>
</address>
<address>
<name>广州</name>
</address>
</list>
</user>
posted on 2016-03-12 12:28 angelshelter 阅读(245) 评论(0) 编辑 收藏 举报