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);
	}
}

你可能感兴趣的:(java)