您的位置:首页 > 编程语言 > Java开发

java中使用JAXP解析xml

2013-01-05 09:16 465 查看
import javax.xml.parsers.DocumentBuilder;

import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Attr;

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;

/**

* 使用JAXP读取XML

*

* @author yuekun

*

*/

public class Demo3 {

public static void main(String[] args) {

try {

// 获取java.xml.parsers.DocumentBuilder类:为加载和分析XML文档提供接口,也就是XML分析程序接口

DocumentBuilderFactory factory = DocumentBuilderFactory

.newInstance();

DocumentBuilder builder = factory.newDocumentBuilder();

// 加载和分析XML文档,如果加载成功则返回一个org.w3c.dom.Document对象

Document document = builder.parse("src/1.xml");

NodeList nodeList = document.getElementsByTagName("*");

NamedNodeMap attributes = null;

//下面是开始遍历NodeList集合

for (int i = 0; i < nodeList.getLength(); i++) {

Node childNode = nodeList.item(i);

String str = null;

if (childNode instanceof Element) {

Element child = (Element) childNode;

if (child.getChildNodes().getLength() > 1) {

str = "Element :" + child.getTagName() + ";";

} else {

str = "Element :" + child.getTagName();

str += " : " + child.getFirstChild().getNodeValue()

+ " ";

}

attributes = child.getAttributes();

for (int j = 0; j < attributes.getLength(); j++) {

Node attr = attributes.item(j);

if (attr instanceof Attr) {

String attrName = attr.getNodeName();

String attrValue = attr.getNodeValue();

str += " Attribute " + attrName + " : "

+ attrValue + ";";

}

}

System.out.println(str);

}

}

} catch (Exception e) {

e.printStackTrace();

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: