Dome4j小例子

package org.hzy.example;

import java.io.File;
import java.net.URI;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

public class Example {
	public Document parse(String url) {
		Document doc = null;
		try {
			// File f=new File(url);
			SAXReader reader = new SAXReader();
			doc = reader.read(url);

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return doc;
	}

	public static void main(String[] args) {
		Example ff = new Example();
		// System.out.println(ff.parse("pets.xml").getRootElement().getName());

//		ff.bar(ff.parse("pets.xml"));
		
		ff.dar(ff.parse("pets.xml"));
		
	}

	public void bar(Document document) {
		try {
			Element root = document.getRootElement();
			// for (Iterator i = root.elementIterator(); i.hasNext();) {
			// Element element = (Element) i.next();
			// for(Iterator j=element.elementIterator("dog");j.hasNext();)
			// {
			// Element ss=(Element)j.next();
			// System.out.println(ss.asXML());
			// }
			//
			// }
			for (Iterator i = root.elementIterator("dogs"); i.hasNext();) {
				Element element = (Element) i.next();
				for (Iterator j = element.elementIterator("dog"); j.hasNext();) {
					Element ss = (Element) j.next();
					System.out.println(ss.asXML());
				}
			}
			// for(Iterator
			// i=root.element("dogs").element("dog").attributeIterator();i.hasNext();)
			// {
			// Attribute attribute = (Attribute) i.next();
			// System.out.println(attribute.getText());
			// }
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

	public void dar(Document doc) {
//		Node node =doc.selectSingleNode("//dog/NAME");
//		System.out.println(node.getText());
		
		List<Node> list=doc.selectNodes("//dog/NAME");
		for (Node node : list) {
			System.out.println(node.getName()+":"+node.getText());
		}
	}
	
	
//	public void treeWalk(Document doc)
//	{
//		treeWalk(doc.getRootElement());
//	}
	
//	public void treeWalk(Element ele)
//	{
//		for(int i=0,size=ele.nodeCount();i<size;i++)
//		{
//			Node node=ele.node(i);
//			if(node instanceof Element)
//			{
//				 System.out.println(node.getName());
//				 treeWalk((Element) node);
//
//			}
//		}
//	}
}

你可能感兴趣的:(dom)