java需要关注的知识点---I0之XML的生成


package com.io;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.List;

import nu.xom.Document;
import nu.xom.Element;
import nu.xom.Serializer;
public class XmlCtrTest {
public static void main(String[] args) throws IOException {
List<Person> people = Arrays.asList(new Person("DR.", "Jie"),
new Person("MJ", "Tim"), new Person("Phillip", "Vic"));
System.out.println(people);
Element root = new Element("people");
for(Person p:people)
root.appendChild(p.getXML());
Document doc = new Document(root);
Person.format(System.out,doc);
Person.format(new BufferedOutputStream(new FileOutputStream("peolple.xml")),doc);

}
}
class Person{
private String firstV,lastV;

public Person(String first, String last) {
super();
this.firstV = first;
this.lastV = last;
}

public Element getXML() {
Element person = new Element("person");
Element first = new Element("first");
first.appendChild(firstV);
Element last = new Element ("last");
last.appendChild(lastV);
person.appendChild(first);
person.appendChild(last);
return person;
}

public String toString() {return firstV + " " + lastV;}
public static void format(OutputStream os,Document doc) throws IOException {
Serializer serializer = new Serializer(os,"ISO-8859-1");
serializer.setIndent(4);
serializer.setMaxLength(60);
serializer.write(doc);
serializer.flush();
}
}

XML读取:

public class ReadXMlExample extends ArrayList<Person>{
public ReadXMlExample(String fileName) throws ValidityException, ParsingException, IOException {
Document doc = new Builder().build(fileName);
Elements elements = doc.getRootElement().getChildElements();
for(int i = 0; i<elements.size(); i++) {
add(new Person(elements.get(i)));
}
}
public static void main(String[] args) throws ValidityException, ParsingException, IOException {
ReadXMlExample rxe = new ReadXMlExample("peolple.xml");
System.out.println(rxe);
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值