1. 程式人生 > >Java編程思想:XML

Java編程思想:XML

orm oot buffere tel flush his catch nts getc

/*
    本次實驗需要在www.xom.nu上下載XOM類庫
 */

import nu.xom.*;

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

public class Test {
    public
static void main(String[] args){ PersonTest.test(); } } class Person { private String first; private String last; public Person(String firstName, String lastName) { this.first =firstName; this.last=lastName; } public Person(Element person) { first
=person.getFirstChildElement("first").getValue(); last=person.getFirstChildElement("last").getValue(); } public Element getXML() { Element person = new Element("person"); Element firstName = new Element("first"); firstName.appendChild(first); Element lastName
= new Element("last"); lastName.appendChild(last); person.appendChild(firstName); person.appendChild(lastName); return person; } public String toString() { return first+" "+last; } 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(); } } class People extends ArrayList<Person> { public People(String fileName) throws 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))); } } } class PersonTest{ public static void test(){ // testToXML(); testFromXML(); } public static void testToXML() { List<Person> persons = Arrays.asList( new Person("A","a"), new Person("B","b"), new Person("C","c") ); System.out.println(persons); Element root = new Element("people"); for (Person p : persons) { root.appendChild(p.getXML()); } Document doc = new Document(root); try { Person.format(System.out,doc); Person.format(new BufferedOutputStream( new FileOutputStream("People.xml")),doc); } catch (IOException e) { e.printStackTrace(); } } public static void testFromXML() { try { People p = new People("People.xml"); System.out.println(p); } catch (ParsingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }

Java編程思想:XML