打印本文 打印本文 关闭窗口 关闭窗口
使用JAXP处理XML文件
作者:武汉SEO闵涛  文章来源:敏韬网  点击数1690  更新时间:2009/4/23 11:18:45  文章录入:mintao  责任编辑:mintao
e())) { customers.addCustomer(UnmarshallCustomer(n)); } else { } } } return customers; } public Customer UnmarshallCustomer(Node customerNode) { Customer customer = new Customer(); Node n; NodeList nodes = customerNode.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { n = nodes.item(i); if ("id".equals(n.getNodeName())) { customer.setId(UnmarshallText(n)); } else if ("name".equals(n.getNodeName())) { customer.setName(UnmarshallText(n)); } else if ("address".equals(n.getNodeName())) { customer.setAddress(UnmarshallText(n)); } } return customer; } public String UnmarshallText(Node textNode) { StringBuffer buf = new StringBuffer(); Node n; NodeList nodes = textNode.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { n = nodes.item(i); if (n.getNodeType() == Node.TEXT_NODE) { buf.append(n.getNodeValue()); } else { } } return buf.toString(); } }

下面是如何驱动DOM去处理xml文件部分。还是先得到一个DocumentBuilderFactory工厂,在用他生成一个DocumentBuilder一个实例,在调用parse方法就可以分析这个xml文件了。

/* 
 * main.java
 * Create @ 2004-4-27 22:18:41
 * by Jiabo
 */
import java.io.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
/**
 * main
 * Create @ 2004-4-27 22:18:41
 * by Jiabo
 */
public class Main {
  public static void main(String args[]) {

    Customers customers = null;
    Document doc = null;
    if (args.length != 1) {
      System.err.println("Usage: cmd filename");
      System.exit(1);
    }
		
    try {
      Unmarshaller handler = new Unmarshaller();
      DocumentBuilderFactory factory = 
	    DocumentBuilderFactory.newInstance();
      DocumentBuilder builder = factory.newDocumentBuilder();
      doc = builder.parse( new File(args[0]) );
			
      customers = handler.UnmarshallCustomers(doc.getDocumentElement());

    } catch (Throwable t) {
      t.printStackTrace();
    }
    System.out.println(customers);
  }
}

总结:

这里是对xml处理的一个简介,力求简介,明了,以最快的速度帮助读者入门,所以,没有完整地使用库中的方法。

Xml文件的处理,对于webservice是基础的基础。而SAX和DOM又是xml处理中基础的基础。浊文请读者笑纳。

参考:

http://java.sun.com/xml/jaxp/docs.html

上一页  [1] [2] 

打印本文 打印本文 关闭窗口 关闭窗口