日期:2014-05-20  浏览次数:20633 次

关于java读取xml
XML code

<?xml version="1.0" encoding="UTF-8"?>
<users>
    <user>
        <id>1</id>
        <username>admin</username>
        <userpass>123456</userpass>
    </user>
    <user>
        <id>2</id>
        <username>zhang</username>
        <userpass>123456</userpass>
    </user>
</users>



自己写的xml

然后想在登录页面登录时候查询xml,看xml中有没有这个user对象,有就返回user对象

怎么弄啊。。。。
给点思路,网上搜的查询代码貌似都不行

------解决方案--------------------
ArrayList<User> list = new ArrayList<User>();

List<Element> idList = doc.selectNodes("//users/user/id");
List<Element> nameList = doc.selectNodes("//users/user/username");
List<Element> passwordList = doc.selectNodes("//users/user/userpass");

int count = idList.size();
for (int i = 0; i < count; i++) {
Element id = idList.get(i);
Element name = nameList.get(i);
Element password = passwordList.get(i);

User user = new User (id.getText());
user .setName(name.getText());
user .setPassword(password.getText());

list.add(user);
}

然后你再把list循环一遍,就知道有没有你的user了。。。。
------解决方案--------------------
Java code

import java.io.*;
import java.util.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;

public class D {
    public static void main(String arge[]) {

        long lasting = System.currentTimeMillis();
        try {
            File f = new File("D://test.xml");
            DocumentBuilderFactory factory = DocumentBuilderFactory
                    .newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(f);
            NodeList nl = doc.getElementsByTagName("user");
            for (int i = 0; i < nl.getLength(); i++) {
                System.out.print("ID:" + doc.getElementsByTagName("id").item(i).getFirstChild().getNodeValue()); 
                System.out.println("username:" + doc.getElementsByTagName("username").item(i).getFirstChild().getNodeValue()); 
                System.out.println("userpass:" + doc.getElementsByTagName("userpass").item(i).getFirstChild().getNodeValue()); 
                                
                
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}