java实现简单解析XML文件功能示例

本文实例讲述了java实现简单解析XML文件功能。分享给大家供大家参考,具体如下:

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的内容:

<?xml version="1.0" encoding="UTF-8"?>

<user>

<usa>

<name>张三</name>

<pass>张三的密码</pass>

</usa>

<usa>

<name>里斯</name>

<pass>里斯的密码</pass>

</usa>

</user>

运行结果:

以上是 java实现简单解析XML文件功能示例 的全部内容, 来源链接: utcz.com/p/215592.html

回到顶部