昨天講解了創建並生成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文件
感謝大家關注
“點讀微訊”