前几天看了编程思想那本书,看到java与XML的交互,使用的是开源XOM,操作都很简单。上网找了一下XOM的介绍,没找到多少,就下面这么点,也许大家都用“dom4j”了吧!
XOM虽然也是一种面向对象的XML API,类似于DOM 的风格,但是它有一些与众不同的特性比如严格保持内存中对象的不变性,从而使XOM实例总是能序列化为正确的XML。此外,与其他Java XML API相比,XOM 追求更简单和更正规。
下面直接看代码使用吧!!
生成XML:
查看复制到剪切板打印
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import nu.xom.*;
class XMLTestWrite {
public static void setXML(Element root) {
Document doc = new Document(root);
try {
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(
"stock.xml"));
Serializer serializer = new Serializer(out, "GB2312");
serializer.setIndent(4);
serializer.setMaxLength(64);
serializer.write(doc);
} catch (IOException ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
Element root = new Element("root");
for (int i = 1; i <= 5; i++) {
Element stock = new Element("stock");
Element code = new Element("code");
Element name = new Element("name");
code.appendChild("stock" + i);
name.appendChild("黄金" + i);
stock.appendChild(code);
stock.appendChild(name);
root.appendChild(stock);
}
setXML(root);
}
}
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import nu.xom.*;
class XMLTestWrite {
public static void setXML(Element root) {
Document doc = new Document(root);
try {
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(
"stock.xml"));
Serializer serializer = new Serializer(out, "GB2312");
serializer.setIndent(4);
serializer.setMaxLength(64);
serializer.write(doc);
} catch (IOException ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
Element root = new Element("root");
for (int i = 1; i <= 5; i++) {
Element stock = new Element("stock");
Element code = new Element("code");
Element name = new Element("name");
code.appendChild("stock" + i);
name.appendChild("黄金" + i);
stock.appendChild(code);
stock.appendChild(name);
root.appendChild(stock);
}
setXML(root);
}
}
读取XML:
查看复制到剪切板打印
class XMLTestRead {
public static String[] getXMLChildList(String FileName) {
Builder builder = new Builder();
Document doc = null;
try {
doc = builder.build(new File(FileName));
} catch (ValidityException e) {
e.printStackTrace();
} catch (ParsingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Element root = doc.getRootElement();
String[] stockCodeArray = null;
if (root != null) {
Elements stocks = root.getChildElements();
stockCodeArray = new String[stocks.size()];
for (int i = 0; i < stocks.size(); i++) {
Element stock = stocks.get(i);
Elements child = stock.getChildElements();
for (int j = 0; j < child.size(); j++) {
String code = child.get(0).getValue();
stockCodeArray[i] = code;
}
}
}
return stockCodeArray;
}
public static void main(String[] args) {
String[] a = getXMLChildList("stock.xml");
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
}
}