w3c.dom组件xml解析实例

w3c.dom组件xml解析实例

 

package com.yanek.demo.xml.test;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import com.sun.org.apache.xerces.internal.parsers.DOMParser;

public class DOMParserBean {

 /**
  * @param args
  */
 public static void main(String[] args) {

  /***********************************************************************
   * <?xml version="1.0" encoding="UTF-8"?> <actions><action path="/test"
   * class="com.mystruts.demo.LoginAction"><forward name="success"
   * url="hello.jsp"/><forward name="fail" url="fail.jsp"/></action><action
   * path="/user" class="com.mystruts.demo.UserAction"><forward
   * name="success" url="list.jsp"/><forward name="fail" url="fail.jsp"/></action></actions>
   */
  try {
   Document document = DOMParserBean.getDocument("d://mystruts.xml");

   NodeList actions = document.getElementsByTagName("action");
   int size = actions.getLength();

   Map result = new HashMap();

   for (int i = 0; i < size; i++) {
    Element xml_action = (Element) actions.item(i);

    System.out.println("class=" + xml_action.getAttribute("class"));
    System.out.println("path=" + xml_action.getAttribute("path"));

    NodeList xml_forwards = xml_action
      .getElementsByTagName("forward");

    for (int j = 0; j < xml_forwards.getLength(); j++) {
     Element forward = (Element) xml_forwards.item(j);

     System.out.println(forward.getAttribute("name"));
     System.out.println(forward.getAttribute("url"));

    }

   }

  } catch (SAXException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

 }

 private DOMParserBean() {
 } // disallow instantiation

 public static Document getDocument(String file) throws SAXException,
   IOException {
  DOMParser parser = new DOMParser();
  parser.parse(new InputSource(new FileInputStream(file)));
  return parser.getDocument();
 }

}

输出:

 

class=com.mystruts.demo.LoginAction
path=/test
success
hello.jsp
fail
fail.jsp
class=com.mystruts.demo.UserAction
path=/user
success
list.jsp
fail
fail.jsp

 

 

 

上一篇:ionic cordova 打包的app图片尺寸


下一篇:解决Macbook Pro 2017安装Windows10双系统后在Windows系统中Apple蓝牙鼠标不能使用问题