您的位置 首页 java

JAVA实现XML(第二天)之——解析XML(含源码)

JAVA实现XML(第二天)之——解析XML(含源码)

昨天讲解了创建并生成XML文件,今天讲解下解析XML文件

JAVA实现XML(第二天)之——解析XML(含源码)

import JAVA . io .FileNotFoundException;

import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;

import javax.xml.parsers.DocumentBuilderFactory;

import javax.xml.parsers.ParserConfigurationException;

import net.sf. json .JSONObject;

import net.sf.json.xml.XMLSerializer;

import org. w3c .dom.Document;

import org.w3c.dom.Node;

import org.w3c.dom.NodeList;

import org.xml.sax.SAXException;

public class ParserXml {

/**

* 解析XML文件

* 2017年4月25日 15:43:19

* @param fileName

*/

public void parserXmldom(String fileName) {

try {

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

DocumentBuilder db = dbf.newDocumentBuilder();

Document document = db.parse(fileName);

NodeList users = document.getChildNodes();

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

Node user = users.item(i);

NodeList userInfo = user.getChildNodes();

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

Node node = userInfo.item(j);

NodeList userMeta = node.getChildNodes();

for (int k = 0; k < userMeta.getLength(); k++) {

if (userMeta.item(k).getNodeName() != “#text”)

System.out.println(userMeta.item(k).getNodeName()

+ “:” + userMeta.item(k).getTextContent());

}

// System.out.println();

}

}

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (ParserConfigurationException e) {

e.printStackTrace();

} catch (SAXException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

}

/**

* @param args

*/

public static void main(String[] args) {

try {

ParserXml j2x = new ParserXml();

String fileName = “file:/D:/程序测试下载/createXML.xml”;

// 数据是全的

j2x.parserXmldom(fileName);

} catch (Exception e) {

e.printStackTrace();

}

}

}

这是打印昨天生成的xml文件

感谢大家关注

“点读微讯”

文章来源:智云一二三科技

文章标题:JAVA实现XML(第二天)之——解析XML(含源码)

文章地址:https://www.zhihuclub.com/184777.shtml

关于作者: 智云科技

热门文章

网站地图