xml解析类,不用任何工具、配置和类库,一个类得到你想要的

来源:互联网 发布:佳能mg2400清零软件 编辑:程序博客网 时间:2024/05/03 08:03

xml文件例子:

 <Menu>
 
  <MenuNode ID="010000" dd="db">
      <Caption>系统管理</Caption>
   <MenuFlag>1</MenuFlag>
   <SubNode ID="010100">   
    <Caption>职工信息</Caption>
    <ID_Model>000001</ID_Model>
    
    <Button ID="010101">
     <Caption>录入</Caption>
     <ID_Model>F010101</ID_Model>
    </Button>
    
    <Button ID="010102">
     <Caption>修改</Caption>
     <ID_Model>F010102</ID_Model>
     <hua HUA="my god"></hua>
    </Button>
    
    <Parameter INDEX="1">
     <TYPE>INT</TYPE>
    </Parameter>
    
   </SubNode>
     </MenuNode>
    
 </Menu>

----------------------------------------------------------------

解析类:

/*
 * Created on 2005-12-15
 */
package com.yx.tool.xml;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 * @author LHH
 * xml文件解析工具类,可以根据一个元素名称和索引位置
 * 返回这个元素所包含的指定名称子元素信息的一个ArrayList列表
 * 子元素信息被封装一个HashMap里,HashMap可以定制以下内容:
 * 该子元素名称、属性和它下一层指定名称子元素的值和属性
 */
public class YxXmlParser {
 static Element root = null;

 public YxXmlParser() {
  try {
   if (root == null) {
    System.out.println("roo is builder!");
    File f = new File(
      "D:/YSGL/TestTag/src/com/yx/tool/xml/data_10k.xml");
    DocumentBuilderFactory factory = DocumentBuilderFactory
      .newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(f);
    root = doc.getDocumentElement();
   }
  } catch (FactoryConfigurationError e) {
   e.printStackTrace();
  } catch (ParserConfigurationException e) {
   e.printStackTrace();
  } catch (SAXException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
 }

 //获取第一层菜单的列表,别修改了,经测试是稳定的   
 public ArrayList getNameList() {
  ArrayList reList = new ArrayList();
  NodeList list = root.getElementsByTagName("MenuNode");//定义第一层菜单元素名称
  for (int i = 0, len = list.getLength(); i < len; i++) {
   HashMap map = new HashMap();
   Node node = list.item(i);
   map.put("name", node.getNodeName());//定制元素名称

   NamedNodeMap nmap = node.getAttributes();
   Node n = nmap.getNamedItem("ID");//定制元素属性
   map.put("ID", n.getNodeValue());
   
   NodeList supList = node.getChildNodes();
   for (int k = 0, klen = supList.getLength(); k < klen; k++) {
    Node supnode = supList.item(k);
    if (supnode.getNodeName().equals("Caption")) {//子定制元素名称
     String cap = supnode.getFirstChild().getNodeValue();
     map.put("capname", cap);
    }
    if (supnode.getNodeName().equals("hua")) {//子定制元素属性
     NamedNodeMap snmap = supnode.getAttributes();
     Node sn = snmap.getNamedItem("HUA");
     map.put("HAIATTR", sn.getNodeValue());
    }
   }
   reList.add(map);
  }

  System.out.println("list.len: " + list.getLength());
  return reList;
 }

 //根据第一层菜单的一个索引值获取第二层菜单的列表
 public ArrayList getNameList(int index) {
  ArrayList reList = new ArrayList();
  NodeList list = root.getElementsByTagName("MenuNode");
  if (index >= list.getLength())
   return null;
  list = ((Element) list.item(index)).getElementsByTagName("SubNode");

  publicMethod(reList, list);

  //公共代码结束     

  return reList;
 }
 
 /**
  * @param reList
  * @param list
  */
 private void publicMethod(ArrayList reList, NodeList list) {
  //以下是公共代码
  for (int i = 0, len = list.getLength(); i < len; i++) {
   HashMap map = new HashMap();
   Node node = list.item(i);
   getNodeInfo(map, node);
   reList.add(map);
  }
 }

 /**
  * @param i
  * @param map
  * @param node
  */
 private void getNodeInfo(HashMap map, Node node) {
  try {
   
            if(node==null)System.out.println("node==null");
            map.put("name", node.getNodeName());
   NamedNodeMap nmap = node.getAttributes();
   if(nmap==null)System.out.println("nmap==null");
   Node n = nmap.getNamedItem("ID");
   if(n==null)System.out.println("n==null");
   map.put("ID", n.getNodeValue());
   NodeList supList = node.getChildNodes();
   for (int k = 0, klen = supList.getLength(); k < klen; k++) {
    Node supnode = supList.item(k);
    if (supnode.getNodeName().equals("Caption")) {
     String cap = supnode.getFirstChild().getNodeValue();
     map.put("capname", cap);
    }
    if (supnode.getNodeName().equals("hua")) {
     NamedNodeMap snmap = supnode.getAttributes();
     Node sn = snmap.getNamedItem("HUA");
     map.put("HAIATTR", sn.getNodeValue());
    }
   }
  } catch (DOMException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }

 //在一个父节点对象基础上,根据子节点名称、属性得到子节点对象
 public Element getNameListbyAttr(Element ele, String name,String attr) {
  ArrayList reList = new ArrayList();
  NodeList list = ele.getElementsByTagName(name);

  //以下是公共代码
  for (int i = 0, len = list.getLength(); i < len; i++) {
   //HashMap map = new HashMap();
   Node node = list.item(i);
   //map.put("name", node.getNodeName());

   NamedNodeMap nmap = node.getAttributes();
   Node n = nmap.getNamedItem("ID");
   String nvalue = n.getNodeValue();
   if(attr.equals(nvalue))return (Element)node;
   
  }

  //公共代码结束     

        return null;
 }
    //在一个父节点对象基础上,根据子节点名称得到子节点对象数组
 public Element[] getNameAllListbyAttr(Element ele, String name) {
  ArrayList reList = new ArrayList();
  NodeList list = ele.getElementsByTagName(name);
  Element[] eles = new Element[list.getLength()];
  //以下是公共代码
  for (int i = 0, len = list.getLength(); i < len; i++) {
   //HashMap map = new HashMap();
   Node node = list.item(i);
            eles[i] = (Element)node;         
  }

  //公共代码结束     

        return eles;
 }

 public ArrayList getList(Element ele){
  ArrayList reList = new ArrayList();
  HashMap map = new HashMap();
  getNodeInfo(map, ele);
  reList.add(map);
  return reList;
 }
 
 //根据第一、二层菜单的2个索引值获取对应第三层菜单的列表
 public ArrayList getNameList(int index1, int index2) {
  ArrayList reList = new ArrayList();
  NodeList list = root.getElementsByTagName("MenuNode");
  if (index1 >= list.getLength())
   return null;
  list = ((Element) list.item(index1)).getElementsByTagName("SubNode");
  if (index2 >= list.getLength())
   return null;
  list = ((Element) list.item(index1)).getElementsByTagName("Button");

  //     以下是公共代码
  for (int i = 0, len = list.getLength(); i < len; i++) {
   HashMap map = new HashMap();
   Node node = list.item(i);
   map.put("name", node.getNodeName());

   NamedNodeMap nmap = node.getAttributes();
   Node n = nmap.getNamedItem("ID");
   map.put("ID", n.getNodeValue());
   NodeList supList = node.getChildNodes();
   for (int k = 0, klen = supList.getLength(); k < klen; k++) {
    Node supnode = supList.item(k);
    if (supnode.getNodeName().equals("Caption")) {
     String cap = supnode.getFirstChild().getNodeValue();
     map.put("capname", cap);
    }
    if (supnode.getNodeName().equals("hua")) {
     NamedNodeMap snmap = supnode.getAttributes();
     Node sn = snmap.getNamedItem("HUA");
     map.put("HAIATTR", sn.getNodeValue());
    }
   }
   reList.add(map);
  }

  //公共代码结束 

  return reList;
 }

 public static void main(String arge[]) {
  long lasting = System.currentTimeMillis();
  long lasting1 = 0;
  try {
   YxXmlParser x = new YxXmlParser();
   lasting1 = System.currentTimeMillis();
   System.out.println("运行时间:" + (System.currentTimeMillis() - lasting));
   //ArrayList list = x.getNameList(0, 0);
   ArrayList list = null;
   Element e = x.getNameListbyAttr(YxXmlParser.root, "MenuNode", "010000");
   e = x.getNameListbyAttr(e, "SubNode", "010100");
   //e = x.getNameListbyAttr(e, "Button", "010102");
   Element es[]= x.getNameAllListbyAttr(e, "Button");
   e = es[0];
   if (e == null) {
    System.out.println("e指定的位置不存在!");
    return;
   }
   list = x.getList(e);

   if (list == null) {
    System.out.println("list指定的位置不存在!");
    return;
   }
   bugInfo(list);
  } catch (Exception e) {
   e.printStackTrace();
  }
  System.out.println("运行时间:" + (System.currentTimeMillis() - lasting1)
    + "毫秒");
 }

 /**
  * @param list
  */
 private static void bugInfo(ArrayList list) {
  for (int i = 0, len = list.size(); i < len; i++) {
   HashMap map = (HashMap) list.get(i);
   System.out.println(map);
   Set set = map.keySet();
   Iterator it = set.iterator();
   while (it.hasNext()) {
    String keystr = (String) it.next();
    System.out.print(keystr + " :   ");
    String str = (String) map.get(keystr);
    System.out.println(str);
   }
  }
 }

}

原创粉丝点击