本文实例讲述了java实现简单解析XML文件功能。分享给大家供大家参考,具体如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
package demo; import java.io.File; import java.io.IOException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class JieXiXML { public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory bdf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = bdf.newDocumentBuilder(); Document document = db.parse( new File( "user.xml" )); NodeList list = document.getElementsByTagName( "usa" ); System.out.println( "服务器之家测试结果:" ); for ( int i = 0 ; i < list.getLength(); i++) { Element element = (Element)list.item(i); String name = element.getElementsByTagName( "name" ).item( 0 ).getFirstChild().getNodeValue(); System.out.println(name); String pass = element.getElementsByTagName( "pass" ).item( 0 ).getFirstChild().getNodeValue(); System.out.println(pass); System.out.println( "------------------" ); } } } |
xml文件user.xml的内容:
1
2
3
4
5
6
7
8
9
10
11
|
<? xml version = "1.0" encoding = "UTF-8" ?> < user > < usa > < name >张三</ name > < pass >张三的密码</ pass > </ usa > < usa > < name >里斯</ name > < pass >里斯的密码</ pass > </ usa > </ user > |
运行结果:
希望本文所述对大家java程序设计有所帮助。
原文链接:http://blog.sina.com.cn/s/blog_6c769cfa0100wqph.html