使用Document Object Model, DOM解析XML文档

也可参考我的新浪博客:http://blog.sina.com.cn/s/blog_43ac5543010190w3.html

 测试代码如下

package main;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;

public class Test {

	public static void main(String[] args) throws Exception {

		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		factory.setIgnoringElementContentWhitespace(true);
		factory.setIgnoringComments(true);
		factory.setValidating(true);

		Document xmlDoc = builder.parse("C:/test.xml");
		Element root = xmlDoc.getDocumentElement();

		listNodes(root, "");
	}

	public static void listNodes(Node node, String space) {
		Element element = null;
		// if (node instanceof Element) {
		if (node.getNodeType() == Node.ELEMENT_NODE) {
			element = (Element) node;
			Text textNode = (Text) element.getFirstChild();
			
			String tagName = element.getTagName();
			String tagValue = textNode.getData().trim();
			System.out.print(space + tagName);
			if (!"".equals(tagValue)) {
				System.out.print("=" + tagValue);
			}
			
			NamedNodeMap attributes = element.getAttributes();
			for (int i = 0; i < attributes.getLength(); i++) {
				Node attribute = attributes.item(i);
				String name = attribute.getNodeName();
				String value = attribute.getNodeValue();
				System.out.print("    " + name + ":" + value);
			}
			System.out.println();
		}

		NodeList list = node.getChildNodes();
		int childNodesLength = list.getLength();
		if (childNodesLength > 0) {
			for (int i = 0; i < childNodesLength; i++) {
				listNodes(list.item(i), space + "    ");
			}
		}
	}
}


 

 

 

JAVA读取XML,JAVA读取XML文档,JAVA解析XML文档,JAVA与XML,XML文档解析(Document Object Model, DOM)_xml