xml tutorials

This commit is contained in:
sxyx2008
2014-07-09 11:07:27 +08:00
parent cafa386420
commit 78e6dd27fc
48 changed files with 2741 additions and 2 deletions
+8
View File
@@ -1,3 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
@@ -9,5 +10,12 @@
<packaging>pom</packaging>
<modules>
<module>xml-stax-example</module>
<module>xml-xom-example</module>
<module>xml-xstream-example</module>
<module>xml-jaxb-example</module>
<module>xml-sax-example</module>
<module>xml-xmlpull-example</module>
<module>xml-dom-example</module>
<module>xml-2-properties</module>
</modules>
</project>
+26
View File
@@ -0,0 +1,26 @@
<?xml version="1.0"?>
<project
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>net.aimeizi</groupId>
<artifactId>xml-tutorials</artifactId>
<version>1.0.0</version>
</parent>
<artifactId>xml-2-properties</artifactId>
<packaging>jar</packaging>
<name>xml-2-properties</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.6</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,26 @@
package org.xml.to.properties;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Properties;
public class Properties2XML {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
Properties props = new Properties();
props.setProperty("email.support", "sxyx2008@163.com");
props.setProperty("email.password", "*********");
props.setProperty("email.host", "smtp.163.com");
props.setProperty("email.port", "25");
OutputStream os = new FileOutputStream("target/email-config.xml");
props.storeToXML(os, "email config","UTF-8");
System.out.println("Done");
}
}
@@ -0,0 +1,33 @@
package org.xml.to.properties;
import java.io.InputStream;
import java.util.Properties;
/**
* xml转properties
* @author welcome
*
*/
public class Xml2Properties {
public static void main(String[] args) throws Exception {
Properties props = new Properties();
InputStream inputStream = ClassLoader.getSystemResourceAsStream("email-config.xml");
props.loadFromXML(inputStream);
String email = props.getProperty("email.address");
String password = props.getProperty("email.password");
String host = props.getProperty("email.host");
String port = props.getProperty("email.port");
System.out.println(email);
System.out.println(password);
System.out.println(host);
System.out.println(port);
}
}
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>Support Email</comment>
<entry key="email.address">sxyx2008@163.com</entry>
<entry key="email.password">*********</entry>
<entry key="email.host">smtp.163.com</entry>
<entry key="email.port">25</entry>
</properties>
+13
View File
@@ -0,0 +1,13 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>net.aimeizi</groupId>
<artifactId>xml-tutorials</artifactId>
<version>1.0.0</version>
</parent>
<artifactId>xml-dom-example</artifactId>
<packaging>jar</packaging>
</project>
@@ -0,0 +1,40 @@
package net.aimeizi.dom.example;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
* 统计元素个数
* @author welcome
*
*/
public class CountXMLElement {
public static void main(String argv[]) {
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(ClassLoader.getSystemResourceAsStream("books.xml"));
NodeList list = doc.getElementsByTagName("book");
System.out.println("Total of elements : " + list.getLength());
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (SAXException sae) {
sae.printStackTrace();
}
}
}
@@ -0,0 +1,50 @@
package net.aimeizi.dom.example;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class DomCreateXML {
public static void main(String[] args) throws Exception{
DocumentBuilder builder=DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = builder.newDocument();
Element rootElement=document.createElement("root");
for (int i = 0; i < 100; i++) {
Element bookElement=document.createElement("book");
bookElement.setAttribute("id", (i+1)+"");
Element nameElement=document.createElement("name");
nameElement.setTextContent("Spring");
Element priceElement=document.createElement("price");
priceElement.setTextContent("88");
Element authorElement=document.createElement("author");
authorElement.setTextContent("李刚");
rootElement.appendChild(bookElement);
bookElement.appendChild(nameElement);
bookElement.appendChild(priceElement);
bookElement.appendChild(authorElement);
}
document.appendChild(rootElement);
TransformerFactory factory=TransformerFactory.newInstance();
Transformer transformer=factory.newTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
transformer.transform(new DOMSource(document), new StreamResult(new File("target/1.xml")));
}
}
@@ -0,0 +1,67 @@
package net.aimeizi.dom.example;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
* 使用dom解析xml
* @author welcome
*
*/
public class DomXmlParser {
public static void main(String[] args) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = null;
try {
documentBuilder = factory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
Document document = null;
try {
document = documentBuilder.parse(ClassLoader.getSystemResourceAsStream("books.xml"));
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Element element = document.getDocumentElement();
NodeList nodeList = element.getElementsByTagName("book");
for (int i = 0; i < nodeList.getLength(); i++) {
Element book = (Element) nodeList.item(i);
String id = book.getAttribute("id");
Element bookname = (Element) book.getElementsByTagName("name")
.item(0);
String name = bookname.getFirstChild().getNodeValue();
Element bookauthor = (Element) book.getElementsByTagName("author")
.item(0);
String author = bookauthor.getFirstChild().getNodeValue();
Element bookprice = (Element) book.getElementsByTagName("price")
.item(0);
String price = bookprice.getFirstChild().getNodeValue();
Element bookpubinfo = (Element) book
.getElementsByTagName("pubinfo").item(0);
String pubinfo = bookpubinfo.getFirstChild().getNodeValue();
System.out.println(id + "," + name + "," + author + "," + price
+ "," + pubinfo);
}
}
}
@@ -0,0 +1,96 @@
package net.aimeizi.dom.example;
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
* 编辑xml
* @author welcome
*
*/
public class ModifyXMLFile {
public static void main(String argv[]) {
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(ClassLoader.getSystemResourceAsStream("file.xml"));
// Get the root element
//Node company = doc.getFirstChild();
// Get the staff element , it may not working if tag has spaces, or
// whatever weird characters in front...it's better to use
// getElementsByTagName() to get it directly.
// Node staff = company.getFirstChild();
// Get the staff element by tag name directly
Node staff = doc.getElementsByTagName("staff").item(0);
// update staff attribute
NamedNodeMap attr = staff.getAttributes();
Node nodeAttr = attr.getNamedItem("id");
nodeAttr.setTextContent("2");
// append a new node to staff
Element age = doc.createElement("age");
age.appendChild(doc.createTextNode("28"));
staff.appendChild(age);
// loop the staff child node
NodeList list = staff.getChildNodes();
for (int i = 0; i < list.getLength(); i++) {
Node node = list.item(i);
// get the salary element, and update the value
if ("salary".equals(node.getNodeName())) {
node.setTextContent("2000000");
}
//remove firstname
if ("firstname".equals(node.getNodeName())) {
staff.removeChild(node);
}
}
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("target/file.xml"));
transformer.transform(source, result);
System.out.println("Done");
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (SAXException sae) {
sae.printStackTrace();
}
}
}
@@ -0,0 +1,33 @@
<?xml version="1.0" encoding="UTF-8"?>
<data>
<book id="1">
<name>Android应用开发详解</name>
<author>json</author>
<price>88</price>
<pubinfo>人民邮电出版社</pubinfo>
</book>
<book id="2">
<name>Android权威指南</name>
<author>tom</author>
<price>79</price>
<pubinfo>人民教育出版社</pubinfo>
</book>
<book id="3">
<name>Android开发案例大全</name>
<author>mark</author>
<price>68</price>
<pubinfo>电子工业出版社</pubinfo>
</book>
<book id="4">
<name>Android从入门到精通</name>
<author>jack</author>
<price>68</price>
<pubinfo>电子工业出版社</pubinfo>
</book>
<book id="5">
<name>Pro Spring</name>
<author>mark</author>
<price>68</price>
<pubinfo>电子工业出版社</pubinfo>
</book>
</data>
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<company>
<staff id="1">
<firstname>yong</firstname>
<lastname>mook kim</lastname>
<nickname>mkyong</nickname>
<salary>100000</salary>
</staff>
</company>
+19
View File
@@ -0,0 +1,19 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>net.aimeizi</groupId>
<artifactId>xml-tutorials</artifactId>
<version>1.0.0</version>
</parent>
<artifactId>xml-jaxb-example</artifactId>
<packaging>jar</packaging>
<dependencies>
<dependency>
<artifactId>junit</artifactId>
<groupId>junit</groupId>
<version>4.6</version>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,45 @@
package net.aimeizi.jaxb.marshaller.example;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import net.aimeizi.jaxb.model.example.ClassRoom;
import net.aimeizi.jaxb.model.example.Student;
import org.junit.Test;
public class JaxbMarshaller {
@Test
public void student2xml() throws JAXBException{
JAXBContext context=JAXBContext.newInstance(Student.class);
Student student=new Student("admin", 18, "陕西西安", new ClassRoom("classroom", "三年二班"));
Marshaller marshaller = context.createMarshaller();
//設置不輸出<?xml version="1.0" encoding="UTF-8" standalone="yes"?>信息
//marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
marshaller.marshal(student, System.out);
}
@Test
public void classroom2xml() throws JAXBException{
JAXBContext context=JAXBContext.newInstance(Student.class);
ClassRoom classRoom=new ClassRoom("classroom", "三年二班");
Student student;
List<Student> students=new ArrayList<Student>();
for (int i = 1; i <= 10; i++) {
student=new Student("admin", 18, "陕西西安");
students.add(student);
}
classRoom.setStudents(students);
Marshaller marshaller = context.createMarshaller();
marshaller.marshal(classRoom, System.out);
}
}
@@ -0,0 +1,70 @@
package net.aimeizi.jaxb.model.example;
import java.util.List;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="classRoom")
public class ClassRoom {
private String classroomid;
private String classroomname;
private List<Student> students;
public ClassRoom() {
}
public ClassRoom(String classroomid, String classroomname) {
super();
this.classroomid = classroomid;
this.classroomname = classroomname;
}
public ClassRoom(String classroomid, String classroomname,
List<Student> students) {
super();
this.classroomid = classroomid;
this.classroomname = classroomname;
this.students = students;
}
public String getClassroomid() {
return classroomid;
}
@XmlAttribute
public void setClassroomid(String classroomid) {
this.classroomid = classroomid;
}
public String getClassroomname() {
return classroomname;
}
@XmlAttribute
public void setClassroomname(String classroomname) {
this.classroomname = classroomname;
}
public List<Student> getStudents() {
return students;
}
@XmlElement(name="student")
public void setStudents(List<Student> students) {
this.students = students;
}
@Override
public String toString() {
return "ClassRoom [classroomid=" + classroomid + ", classroomname="
+ classroomname +"]";
}
}
@@ -0,0 +1,74 @@
package net.aimeizi.jaxb.model.example;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="student")
public class Student {
private String stuname;
private int age;
private String stuaddress;
private ClassRoom room;
public Student() {
}
public Student(String stuname, int age, String stuaddress, ClassRoom room) {
super();
this.stuname = stuname;
this.age = age;
this.stuaddress = stuaddress;
this.room = room;
}
public Student(String stuname, int age, String stuaddress) {
super();
this.stuname = stuname;
this.age = age;
this.stuaddress = stuaddress;
}
public String getStuname() {
return stuname;
}
public void setStuname(String stuname) {
this.stuname = stuname;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getStuaddress() {
return stuaddress;
}
public void setStuaddress(String stuaddress) {
this.stuaddress = stuaddress;
}
public ClassRoom getRoom() {
return room;
}
@XmlElementRef(name="classRoom")
public void setRoom(ClassRoom room) {
this.room = room;
}
@Override
public String toString() {
return "Student [stuname=" + stuname + ", age=" + age + ", stuaddress="
+ stuaddress + ", classroomid=" + room.getClassroomid() + ", classroomname=" + room.getClassroomname()+"]";
}
}
@@ -0,0 +1,35 @@
package net.aimeizi.jaxb.unmarshaller.example;
import java.io.StringReader;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import net.aimeizi.jaxb.model.example.ClassRoom;
import net.aimeizi.jaxb.model.example.Student;
import org.junit.Test;
public class JaxbUnMarshaller {
@Test
public void xml2student() throws JAXBException{
String str="<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><student><age>18</age><classRoom classroomid=\"classroom\" classroomname=\"三年二班\"/><stuaddress>陕西西安</stuaddress><stuname>admin</stuname></student>";
JAXBContext context=JAXBContext.newInstance(Student.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
Student student = (Student) unmarshaller.unmarshal(new StringReader(str));
System.out.println(student);
}
@Test
public void xml2classroom() throws JAXBException{
String str="<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><classRoom classroomid=\"classroom\" classroomname=\"三年二班\"><student><age>18</age><stuaddress>陕西西安</stuaddress><stuname>admin</stuname></student><student><age>18</age><stuaddress>陕西西安</stuaddress><stuname>admin</stuname></student><student><age>18</age><stuaddress>陕西西安</stuaddress><stuname>admin</stuname></student><student><age>18</age><stuaddress>陕西西安</stuaddress><stuname>admin</stuname></student><student><age>18</age><stuaddress>陕西西安</stuaddress><stuname>admin</stuname></student><student><age>18</age><stuaddress>陕西西安</stuaddress><stuname>admin</stuname></student><student><age>18</age><stuaddress>陕西西安</stuaddress><stuname>admin</stuname></student><student><age>18</age><stuaddress>陕西西安</stuaddress><stuname>admin</stuname></student><student><age>18</age><stuaddress>陕西西安</stuaddress><stuname>admin</stuname></student><student><age>18</age><stuaddress>陕西西安</stuaddress><stuname>admin</stuname></student></classRoom>";
JAXBContext context=JAXBContext.newInstance(ClassRoom.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
ClassRoom room = (ClassRoom) unmarshaller.unmarshal(new StringReader(str));
System.out.println(room);
}
}
@@ -0,0 +1,503 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<classRoom classroomid="classroom" classroomname="三年二班">
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
<student>
<age>18</age>
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
</classRoom>
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<student>
<age>18</age>
<classRoom classroomid="classroom" classroomname="三年二班" />
<stuaddress>陕西西安</stuaddress>
<stuname>admin</stuname>
</student>
+20
View File
@@ -0,0 +1,20 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>net.aimeizi</groupId>
<artifactId>xml-tutorials</artifactId>
<version>1.0.0</version>
</parent>
<artifactId>xml-jdom-example</artifactId>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>jdom</groupId>
<artifactId>jdom</artifactId>
<version>1.1</version>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,56 @@
package net.aimeizi.jdom.modify.example;
import java.io.FileWriter;
import java.io.IOException;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
public class ModifyXMLFile {
/**
* @param args
*/
public static void main(String[] args) {
try {
SAXBuilder builder = new SAXBuilder();
Document doc = (Document) builder.build(ClassLoader
.getSystemResource("file.xml"));
Element rootNode = doc.getRootElement();
// update staff id attribute
Element staff = rootNode.getChild("staff");
staff.getAttribute("id").setValue("2");
// add new age element
Element age = new Element("age").setText("28");
staff.addContent(age);
// update salary value
staff.getChild("salary").setText("7000");
// remove firstname element
staff.removeChild("firstname");
XMLOutputter xmlOutput = new XMLOutputter();
// display nice nice
xmlOutput.setFormat(Format.getPrettyFormat());
xmlOutput.output(doc, new FileWriter("target/file.xml"));
// xmlOutput.output(doc, System.out);
System.out.println("File updated!");
} catch (IOException io) {
io.printStackTrace();
} catch (JDOMException e) {
e.printStackTrace();
}
}
}
@@ -0,0 +1,46 @@
package net.aimeizi.jdom.parse.example;
import java.io.IOException;
import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
public class ParseXMLFile {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
SAXBuilder builder = new SAXBuilder();
try {
Document document = (Document) builder.build(ClassLoader.getSystemResource("file.xml"));
Element rootNode = document.getRootElement();
List<Element> list = rootNode.getChildren("staff");
for (int i = 0; i < list.size(); i++) {
Element node = (Element) list.get(i);
System.out.println("First Name : "
+ node.getChildText("firstname"));
System.out.println("Last Name : "
+ node.getChildText("lastname"));
System.out.println("Nick Name : "
+ node.getChildText("nickname"));
System.out.println("Salary : " + node.getChildText("salary"));
System.out.println();
}
} catch (IOException io) {
System.out.println(io.getMessage());
} catch (JDOMException jdomex) {
System.out.println(jdomex.getMessage());
}
}
}
@@ -0,0 +1,53 @@
package net.aimeizi.jdom.write.example;
import java.io.FileWriter;
import java.io.IOException;
import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
public class WriteXMLFile {
public static void main(String[] args) {
try {
Element company = new Element("company");
Document doc = new Document(company);
doc.setRootElement(company);
Element staff = new Element("staff");
staff.setAttribute(new Attribute("id", "1"));
staff.addContent(new Element("firstname").setText("yong"));
staff.addContent(new Element("lastname").setText("mook kim"));
staff.addContent(new Element("nickname").setText("mkyong"));
staff.addContent(new Element("salary").setText("199999"));
doc.getRootElement().addContent(staff);
Element staff2 = new Element("staff");
staff2.setAttribute(new Attribute("id", "2"));
staff2.addContent(new Element("firstname").setText("low"));
staff2.addContent(new Element("lastname").setText("yin fong"));
staff2.addContent(new Element("nickname").setText("fong fong"));
staff2.addContent(new Element("salary").setText("188888"));
doc.getRootElement().addContent(staff2);
// new XMLOutputter().output(doc, System.out);
XMLOutputter xmlOutput = new XMLOutputter();
// display nice nice
xmlOutput.setFormat(Format.getPrettyFormat());
xmlOutput.output(doc, new FileWriter("target/file.xml"));
System.out.println("File Saved!");
} catch (IOException io) {
System.out.println(io.getMessage());
}
}
}
@@ -0,0 +1,15 @@
<?xml version="1.0"?>
<company>
<staff id="1">
<firstname>yong</firstname>
<lastname>mook kim</lastname>
<nickname>mkyong</nickname>
<salary>100000</salary>
</staff>
<staff id="2">
<firstname>low</firstname>
<lastname>yin fong</lastname>
<nickname>fong fong</nickname>
<salary>200000</salary>
</staff>
</company>
+10
View File
@@ -0,0 +1,10 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>net.aimeizi</groupId>
<artifactId>xml-tutorials</artifactId>
<version>1.0.0</version>
</parent>
<artifactId>xml-sax-example</artifactId>
<packaging>jar</packaging>
</project>
@@ -0,0 +1,136 @@
package net.aimeizi.sax.parse.example;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class SaxParseXml extends DefaultHandler {
// 存放遍历集合
private List<Student> list;
// 构建Student对象
private Student student;
// 用来存放每次遍历后的元素名称(节点名称)
private String tagName;
public List<Student> getList() {
return list;
}
public void setList(List<Student> list) {
this.list = list;
}
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
public String getTagName() {
return tagName;
}
public void setTagName(String tagName) {
this.tagName = tagName;
}
// 只调用一次 初始化list集合
@Override
public void startDocument() throws SAXException {
list = new ArrayList<Student>();
}
// 调用多次 开始解析
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if (qName.equals("student")) {
student = new Student();
// 获取student节点上的id属性值
student.setId(Integer.parseInt(attributes.getValue(0)));
// 获取student节点上的group属性值
student.setGroup(Integer.parseInt(attributes.getValue(1)));
}
this.tagName = qName;
}
// 调用多次
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (qName.equals("student")) {
this.list.add(this.student);
}
this.tagName = null;
}
// 只调用一次
@Override
public void endDocument() throws SAXException {
}
// 调用多次
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if (this.tagName != null) {
String date = new String(ch, start, length);
if (this.tagName.equals("name")) {
this.student.setName(date);
} else if (this.tagName.equals("sex")) {
this.student.setSex(date);
} else if (this.tagName.equals("age")) {
this.student.setAge(Integer.parseInt(date));
} else if (this.tagName.equals("email")) {
this.student.setEmail(date);
} else if (this.tagName.equals("birthday")) {
this.student.setBirthday(date);
} else if (this.tagName.equals("memo")) {
this.student.setMemo(date);
}
}
}
public static void main(String[] args) {
SAXParser parser = null;
try {
// 构建SAXParser
parser = SAXParserFactory.newInstance().newSAXParser();
// 实例化 DefaultHandler对象
SaxParseXml parseXml = new SaxParseXml();
// 加载资源文件 转化为一个输入流
InputStream stream = ClassLoader.getSystemResourceAsStream("Student.xml");
// 调用parse()方法
parser.parse(stream, parseXml);
// 遍历结果
List<Student> list = parseXml.getList();
for (Student student : list) {
System.out.println("id:" + student.getId() + "\tgroup:"
+ student.getGroup() + "\tname:" + student.getName()
+ "\tsex:" + student.getSex() + "\tage:"
+ student.getAge() + "\temail:" + student.getEmail()
+ "\tbirthday:" + student.getBirthday() + "\tmemo:"
+ student.getMemo());
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@@ -0,0 +1,62 @@
package net.aimeizi.sax.parse.example;
public class Student {
private int id;
private int group;
private String name;
private String sex;
private int age;
private String email;
private String memo;
private String birthday;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getGroup() {
return group;
}
public void setGroup(int group) {
this.group = group;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getMemo() {
return memo;
}
public void setMemo(String memo) {
this.memo = memo;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
}
@@ -0,0 +1,43 @@
<?xml version="1.0" encoding="UTF-8"?>
<root>
<student id="1" group="1">
<name>张三</name>
<sex>男</sex>
<age>18</age>
<email>zhangsan@163.com</email>
<birthday>1987-06-08</birthday>
<memo>好学生</memo>
</student>
<student id="2" group="2">
<name>李四</name>
<sex>女</sex>
<age>18</age>
<email>lisi@163.com</email>
<birthday>1987-06-08</birthday>
<memo>好学生</memo>
</student>
<student id="3" group="3">
<name>小王</name>
<sex>男</sex>
<age>18</age>
<email>xiaowang@163.com</email>
<birthday>1987-06-08</birthday>
<memo>好学生</memo>
</student>
<student id="4" group="4">
<name>小张</name>
<sex>男</sex>
<age>18</age>
<email>xiaozhang@163.com</email>
<birthday>1987-06-08</birthday>
<memo>好学生</memo>
</student>
<student id="5" group="5">
<name>小明</name>
<sex>男</sex>
<age>18</age>
<email>xiaoming@163.com</email>
<birthday>1987-06-08</birthday>
<memo>好学生</memo>
</student>
</root>
@@ -172,7 +172,7 @@ public class StaxXmlUtil {
@Test
public void xmlStreamWriterXML() throws XMLStreamException, FactoryConfigurationError {
XMLStreamWriter xsw = XMLOutputFactory.newInstance().createXMLStreamWriter(System.out);
xsw.writeStartDocument("GBK","1.0");
xsw.writeStartDocument("utf-8","1.0");
String namespaceURI = "http://blog.csdn.net/jadyer";
xsw.writeStartElement("pre", "uesr", namespaceURI); //再写<pre:uesr>
@@ -192,7 +192,7 @@ public class StaxXmlUtil {
xsw.writeEndElement(); //再写</pre:uesr>
xsw.writeEndDocument(); //先写<?xml version="1.0" encoding="GBK"?>
xsw.writeEndDocument(); //先写<?xml version="1.0" encoding="utf-8"?>
xsw.flush();
xsw.close();
+38
View File
@@ -0,0 +1,38 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>net.aimeizi</groupId>
<artifactId>xml-tutorials</artifactId>
<version>1.0.0</version>
</parent>
<artifactId>xml-xmlpull-example</artifactId>
<packaging>jar</packaging>
<properties>
<xpp3.version>1.1.4c</xpp3.version>
<xmlpull.version>1.1.3.1</xmlpull.version>
<kxml2.version>2.3.0</kxml2.version>
</properties>
<dependencies>
<dependency>
<groupId>xpp3</groupId>
<artifactId>xpp3</artifactId>
<version>${xpp3.version}</version>
</dependency>
<dependency>
<groupId>xmlpull</groupId>
<artifactId>xmlpull</artifactId>
<version>${xmlpull.version}</version>
</dependency>
<dependency>
<groupId>kxml2</groupId>
<artifactId>kxml2</artifactId>
<version>${kxml2.version}</version>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,62 @@
package net.aimeizi.xmlpull.example;
public class Student {
private int id;
private int group;
private String name;
private String sex;
private int age;
private String email;
private String memo;
private String birthday;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getGroup() {
return group;
}
public void setGroup(int group) {
this.group = group;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getMemo() {
return memo;
}
public void setMemo(String memo) {
this.memo = memo;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
}
@@ -0,0 +1,58 @@
package net.aimeizi.xmlpull.example;
import java.io.File;
import java.io.FileOutputStream;
import org.kxml2.io.KXmlSerializer;
import org.xmlpull.v1.XmlSerializer;
/**
* 使用xmlpull api创建xml
* @author welcome
*
*/
public class XmlPullCreateXML {
public static void main(String[] args) throws Exception{
XmlSerializer xmlSerializer=new KXmlSerializer();
xmlSerializer.setOutput(new FileOutputStream(new File("target/student.xml")), "utf-8");
xmlSerializer.startDocument(null, true);
xmlSerializer.startTag(null, "data");
for (int i = 0; i < 10; i++) {
xmlSerializer.startTag(null, "student");
xmlSerializer.attribute(null, "id", ""+(i+1));
xmlSerializer.startTag(null, "name");
xmlSerializer.text("student"+i);
xmlSerializer.endTag(null, "name");
xmlSerializer.startTag(null, "age");
xmlSerializer.text((i+10)+"");
xmlSerializer.endTag(null, "age");
xmlSerializer.startTag(null, "sex");
if(i%2==0){
xmlSerializer.text("女");
}else{
xmlSerializer.text("男");
}
xmlSerializer.endTag(null, "sex");
xmlSerializer.startTag(null, "address");
xmlSerializer.text("陕西西安");
xmlSerializer.endTag(null, "address");
xmlSerializer.endTag(null, "student");
}
xmlSerializer.endTag(null, "data");
xmlSerializer.endDocument();
xmlSerializer.flush();
}
}
@@ -0,0 +1,103 @@
package net.aimeizi.xmlpull.example;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
/**
* 使用xmlpull解析xml
* @author welcome
*
*/
public class XmlPullParseXml {
public List<Student> PullParseXML(){
List<Student> list=null;
Student student = null;
//构建XmlPullParserFactory
try {
XmlPullParserFactory pullParserFactory=XmlPullParserFactory.newInstance();
//获取XmlPullParser的实例
XmlPullParser xmlPullParser=pullParserFactory.newPullParser();
//设置输入流 xml文件
xmlPullParser.setInput(ClassLoader.getSystemResourceAsStream("Student.xml"), "UTF-8");
//开始
int eventType=xmlPullParser.getEventType();
try {
while(eventType!=XmlPullParser.END_DOCUMENT){
String nodeName=xmlPullParser.getName();
switch (eventType) {
//文档开始
case XmlPullParser.START_DOCUMENT:
list=new ArrayList<Student>();
break;
//开始节点
case XmlPullParser.START_TAG:
//判断如果其实节点为student
if("student".equals(nodeName)){
//实例化student对象
student=new Student();
//设置Id属性
student.setId(Integer.parseInt(xmlPullParser.getAttributeValue(0)));
//设置Group属性
student.setGroup(Integer.parseInt(xmlPullParser.getAttributeValue(1)));
}else if("name".equals(nodeName)){
//设置name
student.setName(xmlPullParser.nextText());
}else if("sex".equals(nodeName)){
//设置sex
student.setSex(xmlPullParser.nextText());
}else if("age".equals(nodeName)){
//设置age
student.setAge(Integer.parseInt(xmlPullParser.nextText()));
}else if("email".equals(nodeName)){
//设置email
student.setEmail(xmlPullParser.nextText());
}else if("birthday".equals(nodeName)){
//设置birthday
student.setBirthday(xmlPullParser.nextText());
}else if("memo".equals(nodeName)){
//设置memo属性
student.setMemo(xmlPullParser.nextText());
}
break;
//结束节点
case XmlPullParser.END_TAG:
if("student".equals(nodeName)){
list.add(student);
student=null;
}
break;
default:
break;
}
eventType=xmlPullParser.next();
}
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (XmlPullParserException e) {
e.printStackTrace();
}
return list;
}
public static void main(String[] args) {
List<Student> list=new XmlPullParseXml().PullParseXML();
for(Student student:list){
System.out.println("id:"+student.getId()+"\tgroup:"+student.getGroup()+"\tname:"+student.getName()+"\tsex:"+student.getSex()+"\tage:"+student.getAge()+"\temail:"+student.getEmail()+"\tbirthday:"+student.getBirthday()+"\tmemo:"+student.getMemo());
}
}
}
@@ -0,0 +1,43 @@
<?xml version="1.0" encoding="UTF-8"?>
<root>
<student id="1" group="1">
<name>张三</name>
<sex>男</sex>
<age>18</age>
<email>zhangsan@163.com</email>
<birthday>1987-06-08</birthday>
<memo>好学生</memo>
</student>
<student id="2" group="2">
<name>李四</name>
<sex>女</sex>
<age>18</age>
<email>lisi@163.com</email>
<birthday>1987-06-08</birthday>
<memo>好学生</memo>
</student>
<student id="3" group="3">
<name>小王</name>
<sex>男</sex>
<age>18</age>
<email>xiaowang@163.com</email>
<birthday>1987-06-08</birthday>
<memo>好学生</memo>
</student>
<student id="4" group="4">
<name>小张</name>
<sex>男</sex>
<age>18</age>
<email>xiaozhang@163.com</email>
<birthday>1987-06-08</birthday>
<memo>好学生</memo>
</student>
<student id="5" group="5">
<name>小明</name>
<sex>男</sex>
<age>18</age>
<email>xiaoming@163.com</email>
<birthday>1987-06-08</birthday>
<memo>好学生</memo>
</student>
</root>
+25
View File
@@ -0,0 +1,25 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>net.aimeizi</groupId>
<artifactId>xml-tutorials</artifactId>
<version>1.0.0</version>
</parent>
<artifactId>xml-xom-example</artifactId>
<packaging>jar</packaging>
<dependencies>
<dependency>
<artifactId>junit</artifactId>
<groupId>junit</groupId>
<version>4.6</version>
</dependency>
<dependency>
<groupId>xom</groupId>
<artifactId>xom</artifactId>
<version>1.2.5</version>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,320 @@
package net.aimeizi.xom.example;
import java.io.IOException;
import java.math.BigInteger;
import nu.xom.Attribute;
import nu.xom.Builder;
import nu.xom.Comment;
import nu.xom.DocType;
import nu.xom.Document;
import nu.xom.Element;
import nu.xom.Node;
import nu.xom.ParsingException;
import nu.xom.ProcessingInstruction;
import nu.xom.Serializer;
import nu.xom.Text;
import org.junit.Test;
/**
* @see http://www.xom.nu/tutorial.xhtml
* 使用xom創建xml
* @author scott
*
*/
public class XomCreateXML {
/**
* 最簡單的例子
*/
@Test
public void test01() {
Element root = new Element("root");
root.appendChild("Hello World!");
Document doc = new Document(root);
String result = doc.toXML();
System.out.println(result);
}
/**
* 多個節點
*/
@Test
public void test02() {
BigInteger low = BigInteger.ONE;
BigInteger high = BigInteger.ONE;
Element root = new Element("Fibonacci_Numbers");
for (int i = 1; i <= 10; i++) {
Element fibonacci = new Element("fibonacci");
fibonacci.appendChild(low.toString());
root.appendChild(fibonacci);
BigInteger temp = high;
high = high.add(low);
low = temp;
}
Document doc = new Document(root);
System.out.println(doc.toXML());
}
/**
* 格式化
*/
@Test
public void test03() {
BigInteger low = BigInteger.ONE;
BigInteger high = BigInteger.ONE;
Element root = new Element("Fibonacci_Numbers");
for (int i = 1; i <= 10; i++) {
Element fibonacci = new Element("fibonacci");
fibonacci.appendChild(low.toString());
root.appendChild(fibonacci);
BigInteger temp = high;
high = high.add(low);
low = temp;
}
Document doc = new Document(root);
try {
Serializer serializer = new Serializer(System.out, "ISO-8859-1");
serializer.setIndent(4);
serializer.setMaxLength(64);
serializer.write(doc);
}
catch (IOException ex) {
System.err.println(ex);
}
}
/**
* 屬性
*/
@Test
public void test04() {
BigInteger low = BigInteger.ONE;
BigInteger high = BigInteger.ONE;
Element root = new Element("Fibonacci_Numbers");
for (int i = 1; i <= 10; i++) {
Element fibonacci = new Element("fibonacci");
fibonacci.appendChild(low.toString());
Attribute index = new Attribute("index", String.valueOf(i));
fibonacci.addAttribute(index);
root.appendChild(fibonacci);
BigInteger temp = high;
high = high.add(low);
low = temp;
}
Document doc = new Document(root);
try {
Serializer serializer = new Serializer(System.out, "ISO-8859-1");
serializer.setIndent(4);
serializer.setMaxLength(64);
serializer.write(doc);
} catch (IOException ex) {
System.err.println(ex);
}
}
/**
* 聲明Document Type
*/
@Test
public void test05() {
BigInteger low = BigInteger.ONE;
BigInteger high = BigInteger.ONE;
Element root = new Element("Fibonacci_Numbers");
for (int i = 1; i <= 10; i++) {
Element fibonacci = new Element("fibonacci");
fibonacci.appendChild(low.toString());
Attribute index = new Attribute("index", String.valueOf(i));
fibonacci.addAttribute(index);
root.appendChild(fibonacci);
BigInteger temp = high;
high = high.add(low);
low = temp;
}
Document doc = new Document(root);
DocType doctype = new DocType("Fibonacci_Numbers", "fibonacci.dtd");
doc.insertChild(doctype, 0);
try {
Serializer serializer = new Serializer(System.out, "ISO-8859-1");
serializer.setIndent(4);
serializer.setMaxLength(64);
serializer.write(doc);
} catch (IOException ex) {
System.err.println(ex);
}
}
/**
* Create Document Type
*/
@Test
public void test06() throws Exception{
Element greeting = new Element("greeting");
Document doc = new Document(greeting);
String temp = "<!DOCTYPE element [\n"
+ "<!ELEMENT greeting (#PCDATA)>\n"
+ "]>\n"
+ "<root />";
Builder builder = new Builder();
Document tempDoc = builder.build(temp, null);
DocType doctype = tempDoc.getDocType();
doctype.detach();
doc.setDocType(doctype);
System.out.println(doc.toXML());
}
/**
* Create elements in namespaces
*/
@Test
public void test07() throws Exception{
BigInteger low = BigInteger.ONE;
BigInteger high = BigInteger.ONE;
String namespace = "http://www.w3.org/1998/Math/MathML";
Element root = new Element("mathml:math", namespace);
for (int i = 1; i <= 10; i++) {
Element mrow = new Element("mathml:mrow", namespace);
Element mi = new Element("mathml:mi", namespace);
Element mo = new Element("mathml:mo", namespace);
Element mn = new Element("mathml:mn", namespace);
mrow.appendChild(mi);
mrow.appendChild(mo);
mrow.appendChild(mn);
root.appendChild(mrow);
mi.appendChild("f(" + i + ")");
mo.appendChild("=");
mn.appendChild(low.toString());
BigInteger temp = high;
high = high.add(low);
low = temp;
}
Document doc = new Document(root);
try {
Serializer serializer = new Serializer(System.out, "ISO-8859-1");
serializer.setIndent(4);
serializer.setMaxLength(64);
serializer.write(doc);
}
catch (IOException ex) {
System.err.println(ex);
}
}
/**
* prints all the nodes in a document
*/
@Test
public void test08() throws Exception{
String pageURL="http://localhost:8080/maven-framework/dwr/index.html";
Builder builder = new Builder();
try {
Document doc = builder.build(pageURL);
Element root = doc.getRootElement();
listChildren(root, 0);
}
// indicates a well-formedness error
catch (ParsingException ex) {
System.out.println(pageURL + " is not well-formed.");
System.out.println(ex.getMessage());
} catch (IOException ex) {
System.out.println(ex);
}
}
public static void listChildren(Node current, int depth) {
printSpaces(depth);
String data = "";
if (current instanceof Element) {
Element temp = (Element) current;
data = ": " + temp.getQualifiedName();
}
else if (current instanceof ProcessingInstruction) {
ProcessingInstruction temp = (ProcessingInstruction) current;
data = ": " + temp.getTarget();
}
else if (current instanceof DocType) {
DocType temp = (DocType) current;
data = ": " + temp.getRootElementName();
}
else if (current instanceof Text || current instanceof Comment) {
String value = current.getValue();
value = value.replace('\n', ' ').trim();
if (value.length() <= 20) data = ": " + value;
else data = ": " + current.getValue().substring(0, 17) + "...";
}
// Attributes are never returned by getChild()
System.out.println(current.getClass().getName() + data);
for (int i = 0; i < current.getChildCount(); i++) {
listChildren(current.getChild(i), depth+1);
}
}
private static void printSpaces(int n) {
for (int i = 0; i < n; i++) {
System.out.print(' ');
}
}
/**
* find the title of a web page
*/
@Test
public void test09() throws Exception{
String pageURL="http://localhost:8080/maven-framework/dwr/index.html";
Builder builder = new Builder();
try {
Document doc = builder.build(pageURL);
Element html = doc.getRootElement();
Element head = html.getFirstChildElement("head");
if (head == null) {
head = html.getFirstChildElement("head", "http://www.w3.org/1999/xhtml");
}
Element title = head.getFirstChildElement("title");
if (title == null) {
title = head.getFirstChildElement("title", "http://www.w3.org/1999/xhtml");
}
System.out.println(title.getValue());
}
catch (NullPointerException ex) {
System.err.println(pageURL + " does not have a title.");
}
catch (ParsingException ex) {
System.err.println(pageURL + " is malformed.");
}
catch (IOException ex) {
System.err.println("Could not read " + pageURL);
}
}
}
+30
View File
@@ -0,0 +1,30 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>net.aimeizi</groupId>
<artifactId>xml-tutorials</artifactId>
<version>1.0.0</version>
</parent>
<artifactId>xml-xstream-example</artifactId>
<packaging>jar</packaging>
<dependencies>
<dependency>
<artifactId>junit</artifactId>
<groupId>junit</groupId>
<version>4.6</version>
</dependency>
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>1.4.4</version>
</dependency>
<dependency>
<groupId>org.codehaus.jettison</groupId>
<artifactId>jettison</artifactId>
<version>1.3.3</version>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,35 @@
package net.aimeizi.xstream.annotation.bean2xml.example;
import net.aimeizi.xstream.annotation.example.Person;
import net.aimeizi.xstream.annotation.example.PhoneNumber;
import org.junit.Test;
import com.thoughtworks.xstream.XStream;
/**
* @see http://xstream.codehaus.org/annotations-tutorial.html
* @author scott
*
*/
public class SerializingObject2XML {
@Test
public void test() {
XStream xstream = new XStream();
//XStream xstream = new XStream(new DomDriver()); // does not require XPP3 library
//XStream xstream = new XStream(new StaxDriver()); // does not require XPP3 library starting with Java 6
xstream.processAnnotations(Person.class);
Person joe = new Person("Joe", "Walnes");
joe.setPhone(new PhoneNumber(123, "1234-456"));
joe.setFax(new PhoneNumber(123, "9999-999"));
String xml = xstream.toXML(joe);
System.out.println(xml);
}
}
@@ -0,0 +1,75 @@
package net.aimeizi.xstream.annotation.example;
import com.thoughtworks.xstream.annotations.XStreamAlias;
/**
* @see http://xstream.codehaus.org/annotations-tutorial.html
* @author scott
*
*/
@XStreamAlias("person")
public class Person {
private String firstname;
private String lastname;
@XStreamAlias("phone")
private PhoneNumber phone;
@XStreamAlias("fax")
private PhoneNumber fax;
public Person() {
}
public Person(String firstname, String lastname) {
super();
this.firstname = firstname;
this.lastname = lastname;
}
public Person(String firstname, String lastname, PhoneNumber phone,
PhoneNumber fax) {
super();
this.firstname = firstname;
this.lastname = lastname;
this.phone = phone;
this.fax = fax;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public PhoneNumber getPhone() {
return phone;
}
public void setPhone(PhoneNumber phone) {
this.phone = phone;
}
public PhoneNumber getFax() {
return fax;
}
public void setFax(PhoneNumber fax) {
this.fax = fax;
}
@Override
public String toString() {
return "Person [firstname=" + firstname + ", lastname=" + lastname
+ ", phone=" + phone.getNumber() + ", fax=" + fax.getNumber() + "]";
}
}
@@ -0,0 +1,44 @@
package net.aimeizi.xstream.annotation.example;
import com.thoughtworks.xstream.annotations.XStreamAlias;
/**
* @see http://xstream.codehaus.org/annotations-tutorial.html
* @author scott
*
*/
@XStreamAlias("Phonenumber")
public class PhoneNumber {
private int code;
private String number;
public PhoneNumber() {
}
public PhoneNumber(int code, String number) {
super();
this.code = code;
this.number = number;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
}
@@ -0,0 +1,31 @@
package net.aimeizi.xstream.annotation.xml2bean.example;
import net.aimeizi.xstream.annotation.example.Person;
import org.junit.Test;
import com.thoughtworks.xstream.XStream;
/**
* @see http://xstream.codehaus.org/annotations-tutorial.html
* @author scott
*
*/
public class DeserializingXM2Object {
@Test
public void test() {
XStream xstream = new XStream();
//XStream xstream = new XStream(new DomDriver()); // does not require XPP3 library
//XStream xstream = new XStream(new StaxDriver()); // does not require XPP3 library starting with Java 6
xstream.processAnnotations(Person.class);
String xml="<person><firstname>Joe</firstname><lastname>Walnes</lastname><phone><code>123</code><number>1234-456</number></phone><fax><code>123</code><number>9999-999</number></fax></person>";
Person person = (Person)xstream.fromXML(xml);
System.out.println(person);
}
}
@@ -0,0 +1,36 @@
package net.aimeizi.xstream.bean2xml.example;
import net.aimeizi.xstream.example.Person;
import net.aimeizi.xstream.example.PhoneNumber;
import org.junit.Test;
import com.thoughtworks.xstream.XStream;
/**
* @see http://xstream.codehaus.org/tutorial.html
* @author scott
*
*/
public class SerializingObject2XML {
@Test
public void test() {
XStream xstream = new XStream();
//XStream xstream = new XStream(new DomDriver()); // does not require XPP3 library
//XStream xstream = new XStream(new StaxDriver()); // does not require XPP3 library starting with Java 6
xstream.alias("person", Person.class);
xstream.alias("phonenumber", PhoneNumber.class);
Person joe = new Person("Joe", "Walnes");
joe.setPhone(new PhoneNumber(123, "1234-456"));
joe.setFax(new PhoneNumber(123, "9999-999"));
String xml = xstream.toXML(joe);
System.out.println(xml);
}
}
@@ -0,0 +1,64 @@
package net.aimeizi.xstream.example;
public class Person {
private String firstname;
private String lastname;
private PhoneNumber phone;
private PhoneNumber fax;
public Person() {
}
public Person(String firstname, String lastname) {
super();
this.firstname = firstname;
this.lastname = lastname;
}
public Person(String firstname, String lastname, PhoneNumber phone,
PhoneNumber fax) {
super();
this.firstname = firstname;
this.lastname = lastname;
this.phone = phone;
this.fax = fax;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public PhoneNumber getPhone() {
return phone;
}
public void setPhone(PhoneNumber phone) {
this.phone = phone;
}
public PhoneNumber getFax() {
return fax;
}
public void setFax(PhoneNumber fax) {
this.fax = fax;
}
@Override
public String toString() {
return "Person [firstname=" + firstname + ", lastname=" + lastname
+ ", phone=" + phone.getNumber() + ", fax=" + fax.getNumber() + "]";
}
}
@@ -0,0 +1,35 @@
package net.aimeizi.xstream.example;
public class PhoneNumber {
private int code;
private String number;
public PhoneNumber() {
}
public PhoneNumber(int code, String number) {
super();
this.code = code;
this.number = number;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
}
@@ -0,0 +1,43 @@
package net.aimeizi.xstream.json.example;
import java.io.Serializable;
@SuppressWarnings("serial")
public class Product implements Serializable{
private String id;
private String name;
private double price;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public Product(String id, String name, double price) {
}
public Product() {
}
}
@@ -0,0 +1,25 @@
package net.aimeizi.xstream.json.example;
import org.junit.Test;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;
/**
* @see http://xstream.codehaus.org/json-tutorial.html
* @author scott
*
*/
public class XStreamJson2Object {
@Test
public void test() {
String json = "{\"product\":{\"name\":\"Banana\",\"id\":123"
+ ",\"price\":23.0}}";
XStream xstream = new XStream(new JettisonMappedXmlDriver());
xstream.alias("product", Product.class);
Product product = (Product)xstream.fromXML(json);
System.out.println(product.getName());
}
}
@@ -0,0 +1,38 @@
package net.aimeizi.xstream.json.example;
import org.junit.Test;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;
/**
* @see http://xstream.codehaus.org/json-tutorial.html
* @author scott
*
*/
public class XStreamObject2Json {
@Test
public void test() {
Product product = new Product();
product.setId("123");
product.setName("Banana");
product.setPrice(23.00);
XStream xstream = new XStream(new JettisonMappedXmlDriver());
/*XStream xstream = new XStream(new JsonHierarchicalStreamDriver());*/
/*XStream xstream = new XStream(new JsonHierarchicalStreamDriver() {
public HierarchicalStreamWriter createWriter(Writer writer) {
return new JsonWriter(writer, JsonWriter.DROP_ROOT_MODE);
}
});*/
xstream.setMode(XStream.NO_REFERENCES);
xstream.alias("product", Product.class);
System.out.println(xstream.toXML(product));
}
}
@@ -0,0 +1,30 @@
package net.aimeizi.xstream.xml2bean.example;
import net.aimeizi.xstream.example.Person;
import net.aimeizi.xstream.example.PhoneNumber;
import com.thoughtworks.xstream.XStream;
/**
* @see http://xstream.codehaus.org/tutorial.html
* @author scott
*
*/
public class DeserializingXM2Object {
public static void main(String[] args) {
XStream xstream = new XStream();
//XStream xstream = new XStream(new DomDriver()); // does not require XPP3 library
//XStream xstream = new XStream(new StaxDriver()); // does not require XPP3 library starting with Java 6
xstream.alias("person", Person.class);
xstream.alias("phonenumber", PhoneNumber.class);
String xml="<person><firstname>Joe</firstname><lastname>Walnes</lastname><phone><code>123</code><number>1234-456</number></phone><fax><code>123</code><number>9999-999</number></fax></person>";
Person person = (Person)xstream.fromXML(xml);
System.out.println(person);
}
}