日期:2014-05-20 浏览次数:20786 次
import java.io.*; import javax.xml.parsers.*; import org.w3c.dom.*; public class DomTest { public static void main(String[] args) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(new File("test.xml")); //分析xml文件 Element root = document.getDocumentElement(); //得到根元素 System.out.println(root.getTagName()); //打印根元素标签名 NodeList nodeList = root.getChildNodes(); //得到根元素的子元素 for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (node instanceof Element) //判断子元素是否是Element对象 { Element element = (Element) node; //转化为Element对象 System.out.println(element.getTagName() + " " + element.getAttribute("id") + " " + element.getAttribute("user_agent")); //打印属性 //下面是分析二级子元素,和上面基本相同 NodeList nodeList2 = node.getChildNodes(); for (int j = 0; j < nodeList2.getLength(); j++) { Node node2 = nodeList2.item(j); if (node2 instanceof Element) { Element element2 = (Element) node2; System.out.println(element2.getTagName() + " " + element2.getAttribute("timestamp") + " " + element2.getAttribute("type")); } } } } } }
------解决方案--------------------
用dom4j解析即可,网上有很多例子,LZ搜dom4j解析xml文件,能搜到好多。
比如:http://wenku.baidu.com/view/4dd4ee3067ec102de2bd898b.html
dom4j也有官方的文档与例子。http://www.dom4j.org/