XStream 非常简单实用的XML读写工具(一)
最近工作内容需要对Java对象做XML输出,公司里常用的两种框架是XStream和XML Beans。两种都我都用了,对于普通的,schema不是很复杂的XML文件来说选择XStream更方便。这篇文章先介绍一下XStream的用法,XML Beans的用法另外再介绍。
1. 先给个要输出的xml文档的例子:
<students>
<student>
<name>Peter</name>
<id>1001</id>
<age>15</age>
<student>
<student>
<name>Mike</name>
<id>1002</id>
<age>16</age>
<student>
<students>
2. 首先定义两个类:Students和Student,其中Students有一个List<Student>,Student有三个Field:name,id,age
public class Students {
List studentList;
public Students() {
studentList = new ArrayList();
}
public void addStudent(Student p) {
studentList.add(p);
}
}
public class Student {
private String name, id, age;
public Student(String name, String id, String age){
this.name = name;
this.id = id;
this.age = age;
}
//Setter and Getter for name, id, age
......
}
3. 使用XStream将Object写入XML:
//XStream实例
XStream xStream = new XStream();
//定义xml的根节点"Students"
Students root = new Students();
//定义根节点的两个子节点"Student"
Student peter = new Student("peter", "1001", "15");
Student mike = new Student("mike", "1002", "16");
//添加到根节点上
root.addStudent(peter);
root.addStudent(mike);
//
System.out.println(xStream.toXML(root));
4. 输出的结果和我们的期待的并不完全一样:
<de.dexin.student.Students>
<studentList>
<de.dexin.student.Student>
<name>peter</name>
<id>1001</id>
<age>15</age>
</de.dexin.student.Student>
<de.dexin.student.Student>
<name>mike</name>
<id>1002</id>
<age>16</age>
<
相关文档:
文章来源:IT工程技术网 http://www.systhinker.com/html/43/n-11643.html
用的是一种很笨的方法,但可以帮助初学者了解访问XML节点的过程。
已知有一个XML文件(bookstore.xml)如下:
<?xml version="1.0" encoding="gb2312"?>
<bookstore>
<book genre="fantasy" ISBN="2-3631-4">
......
String userId = request.getParameter("userId");
System.out.println(userId);
response.setCharacterEncoding("UTF-8");
//response.getWriter().println("hello world -- 我爱你。。。");
String xml = "<user>" +
"<username>涛哥</username>" +
"</user>";
respon ......
Product.xml
<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/css" href="product.css" ?>
<productata>
<product prodid="p001" category="toy">
<productname>Mini Bus</productname>
<description>This is a toy for childern aged 4 and above&l ......
ID.xml
<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/css" href="ID.css"?>
<bookdetail>
<book class="A" id="B1">
<author>曹雪芹</author>
<title>红楼梦</title>
<price>60.00</price>
</book>
<book class="A ......
XML文件由于其扩展性与兼容性的优点,被广泛用作软件和系统的配置文件。这里简要介绍一下QT下如何来解析XML文件。
源代码:
xml_reader.h
#ifndef XML_READER_H
#define XML_READER_H
#include <QtCore>
//#include <QtGui>
class xml_reader : public QXmlStreamReader
{
//Q_OBJECT
public:
......