java访问xml文件
package com.luqin.java.common.xml;import java.io.*;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.Node;import org.w3c.dom.NodeList;public class XmlJava {public static void main(String args[]) {Element element = null;File f = new File("a.xml");DocumentBuilder db = null; // documentBuilder为抽象不能直接实例化(将XML文件转换为DOM文件)DocumentBuilderFactory dbf = null;try {dbf = DocumentBuilderFactory.newInstance(); // 返回documentBuilderFactory对象db = dbf.newDocumentBuilder();// 返回db对象用documentBuilderFatory对象获得返回documentBuildr对象Document dt = db.parse(f); // 得到一个DOM并返回给document对象element = dt.getDocumentElement();// 得到一个elment根元素System.out.println("根元素:" + element.getNodeName()); // 获得根节点NodeList childNodes = element.getChildNodes(); // 获得根元素下的子节点for (int i = 0; i < childNodes.getLength(); i++) { // 遍历这些子节点Node node1 = childNodes.item(i); // childNodes.item(i);// 获得每个对应位置i的结点if ("Account".equals(node1.getNodeName())) { // 如果节点的名称为"Account",则输出Account元素属性typeSystem.out.println("\r\n找到一篇账号. 所属区域: "+ node1.getAttributes().getNamedItem("type").getNodeValue() + ". ");NodeList nodeDetail = node1.getChildNodes(); // 获得// <Accounts>下的节点for (int j = 0; j < nodeDetail.getLength(); j++) { // 遍历// <Accounts>下的节点Node detail = nodeDetail.item(j); // 获得// <Accounts>元素每一个节点if ("code".equals(detail.getNodeName())) // 输出codeSystem.out.println("卡号: " + detail.getTextContent());else if ("pass".equals(detail.getNodeName())) // 输出passSystem.out.println("密码: " + detail.getTextContent());else if ("name".equals(detail.getNodeName())) // 输出nameSystem.out.println("姓名: " + detail.getTextContent());else if ("money".equals(detail.getNodeName())) // 输出moneySystem.out.println("余额: " + detail.getTextContent());}}}} catch (Exception e) {System.out.println(e);}}}
<?xml version="1.0" encoding="gbk"?><Accounts><Account type="by0003"><code>100001</code><pass>123</pass><name>李四</name><money>1000000.00</money></Account><Account type="hz0001"><code>100002</code><pass>123</pass><name>张三</name><money>1000.00</money></Account></Accounts>