〖JAVA经验〗JAVA技巧:dom解析xml文件实现代码

代码如下:

package com.yangrs;

import java.io.IOException;

import javax.xml.parsers.*;

import org.w3c.dom.*;

import org.xml.sax.SAXException;

public class DomTest {

public static void main(String[] args) {

try {

javax.xml.parsers.DocumentBuilderFacTory dbf = DocumentBuilderFacTory

.newInstance();

DocumentBuilder db = dbf.newDocumentBuilder();

org.w3c.dom.Document dom = db.parse(“myxml1.xml”);

System.out.println(“文件路径:” + dom.getDocumentURI());

org.w3c.dom.Element root = dom.getDocumentElement();

IteraTor(root); //循环迭代

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

// System.out.println(nodelist.item(i).getNodeName());

// System.out.println(nodelist.item(i).getNodeValue());

// System.out.println(nodelist.item(i).getTextContent());//这里才取得了每个结点的值

//

// //会有七个节点,because空格也算

// NodeList childlist = nodelist.item(i).getChildNodes();

//

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

// System.out.println(childlist.item(j).getNodeName());

// }

//

// }

} catch (ParserConfigurationException e) {

e.printStackTrace();

} catch (SAXException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

}

/**

* 做循环使用

*

* @param root

* 传入的元素

*/

public static void IteraTor(Element root) {

NodeList nodelist = root.getChildNodes();

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

Node node = nodelist.item(i);

if (node instanceof Text) {

String value = node.getNodeValue();

if (value != null && !value.trim().equals(“”)) {

System.out.println(“文本:” + value);

}

}

if (node instanceof Element) {

System.out.println(“节点:” + node.getNodeName());

IteraTor((Element) node);

}

}

}

一起交流学习请访问:Tore_m_1206686_21115_1_1.html”>http://www.shangxueba.com/sTore_m_1206686_21115_1_1.html

只有一条路不能拒绝——那就是成长的路。

〖JAVA经验〗JAVA技巧:dom解析xml文件实现代码

相关文章:

你感兴趣的文章:

标签云: