jxpengtao 发表于 2013-1-27 04:48:29

java中解析xml

public class Test {
    public static void main(String[] arc) throws RuntimeException {

      try {
            SAXReader reader = new SAXReader();
            //以下是要输入的xml
            org.dom4j.Document doc = reader.read("C:\\11.xml");
            String aa = doc.asXML();
            EntrustUpLoadCommand pd = new EntrustUpLoadCommand();
            pd.setXML(aa);
            pd = (EntrustUpLoadCommand) pd.execute();
      } catch (Exception e) {
            e.printStackTrace();
      }
    }
}

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

    //用于把xml文件中属性值转为map 其中 name为map的key,value为map中的value
public static Map getProperties(String xml) throws CommandException {
      Map prop = new HashMap();
      try {
            SAXBuilder builder = new SAXBuilder();
            Document doc = builder.build(new StringReader(xml));
            Element root = doc.getRootElement();
            Element pro = root.getChild("properties");
            if (null != pro) {
                List proList = pro.getChildren("cell");


                for (int i = 0; i < proList.size(); i++) {
                  Element cell = (Element) proList.get(i);
                  prop.put(cell.getAttributeValue("name").toLowerCase(), cell.getAttributeValue("value"));
                }
            }

            getvoList(root, prop);
      } catch (JDOMException e) {
            throw new CommandException("XML报文有问题");
      }

      return prop;
    }

    //用于把Element文件中属性值转为map[] 其中 name为map的key,value为map中的value
    //此方法主要是单list转map
private static void getvoList(Element root, Map in) throws CommandException {

      try {
            List pro = root.getChildren("arrayList");
            log.debug("pro.size() = " + (null == pro ? "0" : "" + pro.size()));
            if (null != pro) {
                for (int k = 0; k < pro.size(); k++) {
                  List prop = new ArrayList();
                  Element prof = (Element) pro.get(k);
                  in.put(prof.getAttributeValue("name"), prop);
                  List pror = prof.getChildren("vo");
                  for (int j = 0; j < pror.size(); j++) {
                        Element proc = (Element) pror.get(j);
                        List proList = proc.getChildren("cell");
                        Map propc = new HashMap();
                        if (null != proList) {
                            for (int i = 0; i < proList.size(); i++) {
                              Element cell = (Element) proList.get(i);
                              propc.put(cell.getAttributeValue("name").toLowerCase(), cell.getAttributeValue("value"));
                            }
                            prop.add(propc);
                        }
                        getvoList2(proc,in);//-----------
                  }

                }
            }
      } catch (Exception e) {
            throw new CommandException("XML报文解析vo有问题");
      }

    }
页: [1]
查看完整版本: java中解析xml