NanoXML组件解析xml实例

NanoXML组件解析xml实例:

noaoxml组件对xml格式的字符串解析,效率很高

 

代码如下:

 

package com.yanek.demo.xml.test;

import java.util.Vector;

import javolution.context.ObjectFactory;
import net.n3.nanoxml.IXMLElement;
import net.n3.nanoxml.IXMLParser;
import net.n3.nanoxml.IXMLReader;
import net.n3.nanoxml.StdXMLReader;
import net.n3.nanoxml.XMLException;
import net.n3.nanoxml.XMLParserFactory;

import org.apache.log4j.Logger;

 

public class NanoXMLTest {

 private static Logger logger = Logger
   .getLogger(NanoXMLTest.class.getName());

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

 
  String config = "<actions id=/"123/" name=/"test/"><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>";
  IXMLParser xmlParser = null;
  IXMLReader xmlReader = null;
  
  long a = System.currentTimeMillis();
  xmlParser = NanoXMLTest.XMLPARSER_FACTORY.object();
  
  xmlReader = StdXMLReader.stringReader(config);
  xmlParser.setReader(xmlReader);
  try {
   IXMLElement root = (IXMLElement)xmlParser.parse();
   
   System.out.println(root.getAttribute("id", ""));
   System.out.println(root.getAttribute("name", ""));
   
   Vector actions= root.getChildrenNamed("action");
   
   for (int i=0;i<actions.size();i++)
   {
    IXMLElement action = (IXMLElement)actions.elementAt(i);
    
    System.out.println(action.getAttribute("path", ""));
    System.out.println(action.getAttribute("class", ""));
    
    
    Vector forwards=action.getChildrenNamed("forward");
    for (int j=0;j<actions.size();j++)
    {
     
     IXMLElement forward = (IXMLElement)forwards.elementAt(j);
     
     System.out.println(forward.getAttribute("name", ""));
     System.out.println(forward.getAttribute("url", "")); 
    }
    
    
    
   }
   
   

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

 public static ObjectFactory<IXMLParser> XMLPARSER_FACTORY = new ObjectFactory<IXMLParser>() {
  protected IXMLParser create() {
   try {
    return XMLParserFactory.createDefaultXMLParser();
   } catch (ClassNotFoundException e) {
    logger.error(e);
   } catch (InstantiationException e) {
    logger.error(e);
   } catch (IllegalAccessException e) {
    logger.error(e);
   }
   return null;
  }
 };

}

 

输出:

 

123
test
/test
com.mystruts.demo.LoginAction
success
hello.jsp
fail
fail.jsp
/user
com.mystruts.demo.UserAction
success
list.jsp
fail
fail.jsp

 

上一篇:w3c.dom组件写xml文件实例


下一篇:flume1.6 centos6.x 安装与配置