xml的解析方法及源代码

xml的解析方法及源代码

第一种:SAX解析
SAX处理机制:SAX是一种基于事件驱动的API。利用SAX解析XML文档,牵涉到两个部分:解析器和事件处理器。解析器负责读取XML文档,并向事件处理器发生事件,如元素开始和元素结束事件;而事件处理器则负责对事件做出响应,对传递的XML数据进行处理。

测试用的xml文件:db.xml

Xml代码 复制代码

<?xml version="1.0" encoding="UTF-8"?>  

<!--<!DOCTYPE dbconfig SYSTEM "db.dtd">-->  

<dbconfig>  

 <db type="oracle">  

  <driver>oracle.jdbc.driver.OracleDriver</driver>  

  <url>jdbc:oracle:thin:@localhost:1521:oracle</url>  

  <user>scott</user>  

  <password>tiger</password>  

 </db>  

</dbconfig>  

<?xml version="1.0" encoding="UTF-8"?>
<!--<!DOCTYPE dbconfig SYSTEM "db.dtd">-->
<dbconfig>
 <db type="oracle">
  <driver>oracle.jdbc.driver.OracleDriver</driver>
  <url>jdbc:oracle:thin:@localhost:1521:oracle</url>
  <user>scott</user>
  <password>tiger</password>
 </db>
</dbconfig>

DTD文件db.dtd

Xml代码 复制代码

<!ELEMENT dbconfig (db+)>  

<!ELEMENT db (driver,url,user,password)>  

<!ELEMENT driver (#PCDATA)>  

<!ELEMENT url (#PCDATA)>  

<!ELEMENT user (#PCDATA)>  

<!ELEMENT password (#PCDATA)>  

<!ATTLIST db type CDATA #REQUIRED>  

<!ELEMENT dbconfig (db+)>
<!ELEMENT db (driver,url,user,password)>
<!ELEMENT driver (#PCDATA)>
<!ELEMENT url (#PCDATA)>
<!ELEMENT user (#PCDATA)>
<!ELEMENT password (#PCDATA)>
<!ATTLIST db type CDATA #REQUIRED>

SAX解析实例一
org.xml.sax.DefalutHandler类:  可以扩展该类,给出自己的解析实现
SAXPrinter.java

Java代码 复制代码

import java.io.File;   

  

import javax.xml.parsers.SAXParser;   

import javax.xml.parsers.SAXParserFactory;   

  

import org.xml.sax.Attributes;   

import org.xml.sax.SAXException;   

import org.xml.sax.helpers.DefaultHandler;   

  

public class SAXPrinter extends DefaultHandler   

{   

  

  /** *//**  

   * 文档开始事件  

   */  

    public void startDocument() throws SAXException   

    {   

        System.out.println("<?xml version=\"1.0\" encoding=\"utf-8\"?>");   

    }   

       

  /** *//**  

   * 接收处理指令事件  

   */  

    public void processingInstruction(String target, String data) throws SAXException   

    {   

        System.out.println("<?"+target+" "+data+"?>");   

    }   

       

  /** *//**  

   * 元素开始事件  

  * 参数说明:  

   *   uri - 名称空间 URI,如果元素没有任何名称空间 URI,或者没有正在执行名称空间处理,则为空字符串。  

   *   localName - 本地名称(不带前缀),如果没有正在执行名称空间处理,则为空字符串。  

   *   qName - 限定的名称(带有前缀),如果限定的名称不可用,则为空字符串。  

   *   attributes - 附加到元素的属性。如果没有属性,则它将是空的 Attributes 对象。  

   */  

    public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException   

    {   

        System.out.print("<"+qName);//输出元素名称   

        int len=attrs.getLength();//元素属性列表长度   

           

    //利用循环输出属性列表   

        for(int i=0;i<len;i++)   

        {   

            System.out.print(" ");   

            System.out.print(attrs.getQName(i));   

            System.out.print("=\"");   

            System.out.print(attrs.getValue(i));   

            System.out.print("\"");   

        }   

        System.out.print(">");   

    }   

       

  /** *//**  

   * 元素中字符数据事件:接收元素中字符数据  

   * 注意:1.应用程序不要试图读取ch数组指定范围外的数据,(即start至length之外)  

   *      2.有些解析器将使用ignorableWhitespace()方法来报告元素内容中的空白,而不是characters()方法,如:进行有效性验证的解析器  

   */  

    public void characters(char[] ch, int start, int length) throws SAXException   

    {   

        System.out.print(new String(ch,start,length));   

    }   

  

  /** *//**  

   * 结束元素事件  

   */  

    public void endElement(String uri, String localName, String qName) throws SAXException   

    {   

        System.out.print("</"+qName+">");   

    }   

 

    public static void main(String[] args)   

    {   

       SAXParserFactory spf=SAXParserFactory.newInstance();   

           

        try  

        {   

        SAXParser sp=spf.newSAXParser();   

          sp.parse(new File("db.xml"),new SAXPrinter());   

       }   

        catch (Exception e)   

        {   

            e.printStackTrace();   

        }   

    }   

}  

import java.io.File;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class SAXPrinter extends DefaultHandler
{

  /** *//**
   * 文档开始事件
   */
    public void startDocument() throws SAXException
    {
        System.out.println("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
    }
    
  /** *//**
   * 接收处理指令事件
   */
    public void processingInstruction(String target, String data) throws SAXException
    {
        System.out.println("<?"+target+" "+data+"?>");
    }
    
  /** *//**
   * 元素开始事件
   * 参数说明:
   *   uri - 名称空间 URI,如果元素没有任何名称空间 URI,或者没有正在执行名称空间处理,则为空字符串。
   *   localName - 本地名称(不带前缀),如果没有正在执行名称空间处理,则为空字符串。
   *   qName - 限定的名称(带有前缀),如果限定的名称不可用,则为空字符串。
   *   attributes - 附加到元素的属性。如果没有属性,则它将是空的 Attributes 对象。
   */
    public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException
    {
        System.out.print("<"+qName);//输出元素名称
        int len=attrs.getLength();//元素属性列表长度
        
    //利用循环输出属性列表
        for(int i=0;i<len;i++)
        {
            System.out.print(" ");
            System.out.print(attrs.getQName(i));
            System.out.print("=\"");
            System.out.print(attrs.getValue(i));
            System.out.print("\"");
        }
        System.out.print(">");
    }
    
  /** *//**
   * 元素中字符数据事件:接收元素中字符数据
   * 注意:1.应用程序不要试图读取ch数组指定范围外的数据,(即start至length之外)
   *      2.有些解析器将使用ignorableWhitespace()方法来报告元素内容中的空白,而不是characters()方法,如:进行有效性验证的解析器
   */
    public void characters(char[] ch, int start, int length) throws SAXException
    {
        System.out.print(new String(ch,start,length));
    }

  /** *//**
   * 结束元素事件
   */
    public void endElement(String uri, String localName, String qName) throws SAXException
    {
        System.out.print("</"+qName+">");
    }

    public static void main(String[] args)
    {
        SAXParserFactory spf=SAXParserFactory.newInstance();
        
        try
        {
            SAXParser sp=spf.newSAXParser();
            sp.parse(new File("db.xml"),new SAXPrinter());
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

SAX解析实例二
org.xml.sax.ContentHandler接口: 通过实现该接口给出自己的解析实现。
org.xml.sax.ErrorHandler接口:如果SAX应用程序需要实现定制的错误处理,那么它必须实现这个接口,并调用XMLReader对象的setErrorHandler()方法向解析器注册异常处理实例,这样,解析器将通过这个接口报告所有的错误和警告。
ContentHandlerImpl.java

Java代码 复制代码
  1. import org.xml.sax.Attributes;   
  2. import org.xml.sax.ContentHandler;   
  3. import org.xml.sax.Locator;   
  4. import org.xml.sax.SAXException;   
  5.   
  6. public class ContentHandlerImpl implements ContentHandler   
  7. {   
  8.   /** *//**  
  9.    * 文档开始事件  
  10.    */  
  11.   public void startDocument() throws SAXException   
  12.   {   
  13.     System.out.println("<?xml version=\"1.0\" encoding=\"utf-8\"?>");   
  14.   }   
  15.      
  16.   /** *//**  
  17.    * 接收处理指令事件  
  18.    */  
  19.   public void processingInstruction(String target, String data) throws SAXException   
  20.   {   
  21.     System.out.println("<?"+target+" "+data+"?>");   
  22.   }   
  23.      
  24.   /** *//**  
  25.    * 元素开始事件  
  26.    * 参数说明:  
  27.    *   uri - 名称空间 URI,如果元素没有任何名称空间 URI,或者没有正在执行名称空间处理,则为空字符串。  
  28.    *   localName - 本地名称(不带前缀),如果没有正在执行名称空间处理,则为空字符串。  
  29.    *   qName - 限定的名称(带有前缀),如果限定的名称不可用,则为空字符串。  
  30.    *   attributes - 附加到元素的属性。如果没有属性,则它将是空的 Attributes 对象。  
  31.    */  
  32.   public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException   
  33.   {   
  34.     System.out.print("<"+qName);//输出元素名称   
  35.     int len=attrs.getLength();//元素属性列表长度   
  36.        
  37.     //利用循环输出属性列表   
  38.     for(int i=0;i<len;i++)   
  39.     {   
  40.       System.out.print(" ");   
  41.       System.out.print(attrs.getQName(i));   
  42.       System.out.print("=\"");   
  43.       System.out.print(attrs.getValue(i));   
  44.       System.out.print("\"");   
  45.     }   
  46.     System.out.print(">");   
  47.   }   
  48.      
  49.   /** *//**  
  50.    * 元素中字符数据事件:接收元素中字符数据  
  51.    * 注意:1.应用程序不要试图读取ch数组指定范围外的数据,(即start至length之外)  
  52.    *      2.有些解析器将使用ignorableWhitespace()方法来报告元素内容中的空白,而不是characters()方法,如:进行有效性验证的解析器  
  53.    */  
  54.   public void characters(char[] ch, int start, int length) throws SAXException   
  55.   {   
  56.     System.out.print(new String(ch,start,length));   
  57.   }   
  58.   
  59.   /** *//**  
  60.    * 结束元素事件  
  61.    */  
  62.   public void endElement(String uri, String localName, String qName) throws SAXException   
  63.   {   
  64.     System.out.print("</"+qName+">");   
  65.   }   
  66.   
  67.   public void endDocument() throws SAXException   
  68.   {   
  69.        
  70.   }   
  71.   
  72.   public void endPrefixMapping(String prefix) throws SAXException   
  73.   {   
  74.        
  75.   }   
  76.   
  77.   public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException   
  78.   {   
  79.        
  80.   }   
  81.   
  82.   public void setDocumentLocator(Locator locator)   
  83.   {   
  84.        
  85.   }   
  86.   
  87.   public void skippedEntity(String name) throws SAXException   
  88.   {   
  89.        
  90.   }   
  91.   
  92.   public void startPrefixMapping(String prefix, String uri) throws SAXException   
  93.   {   
  94.        
  95.   }   
  96.   
  97. }   
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;

public class ContentHandlerImpl implements ContentHandler
{
  /** *//**
   * 文档开始事件
   */
  public void startDocument() throws SAXException
  {
    System.out.println("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
  }
  
  /** *//**
   * 接收处理指令事件
   */
  public void processingInstruction(String target, String data) throws SAXException
  {
    System.out.println("<?"+target+" "+data+"?>");
  }
  
  /** *//**
   * 元素开始事件
   * 参数说明:
   *   uri - 名称空间 URI,如果元素没有任何名称空间 URI,或者没有正在执行名称空间处理,则为空字符串。
   *   localName - 本地名称(不带前缀),如果没有正在执行名称空间处理,则为空字符串。
   *   qName - 限定的名称(带有前缀),如果限定的名称不可用,则为空字符串。
   *   attributes - 附加到元素的属性。如果没有属性,则它将是空的 Attributes 对象。
   */
  public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException
  {
    System.out.print("<"+qName);//输出元素名称
    int len=attrs.getLength();//元素属性列表长度
    
    //利用循环输出属性列表
    for(int i=0;i<len;i++)
    {
      System.out.print(" ");
      System.out.print(attrs.getQName(i));
      System.out.print("=\"");
      System.out.print(attrs.getValue(i));
      System.out.print("\"");
    }
    System.out.print(">");
  }
  
  /** *//**
   * 元素中字符数据事件:接收元素中字符数据
   * 注意:1.应用程序不要试图读取ch数组指定范围外的数据,(即start至length之外)
   *      2.有些解析器将使用ignorableWhitespace()方法来报告元素内容中的空白,而不是characters()方法,如:进行有效性验证的解析器
   */
  public void characters(char[] ch, int start, int length) throws SAXException
  {
    System.out.print(new String(ch,start,length));
  }

  /** *//**
   * 结束元素事件
   */
  public void endElement(String uri, String localName, String qName) throws SAXException
  {
    System.out.print("</"+qName+">");
  }

  public void endDocument() throws SAXException
  {
    
  }

  public void endPrefixMapping(String prefix) throws SAXException
  {
    
  }

  public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException
  {
    
  }

  public void setDocumentLocator(Locator locator)
  {
    
  }

  public void skippedEntity(String name) throws SAXException
  {
    
  }

  public void startPrefixMapping(String prefix, String uri) throws SAXException
  {
    
  }

} 

ErrorHandlerImpl.java 

Java代码 复制代码
  1. public class ErrorHandlerImpl implements ErrorHandler   
  2. {   
  3.   
  4.   public void warning(SAXParseException e) throws SAXException   
  5.   {   
  6.     System.out.println("[Warning ]"+getLocationString(e)+":"+e.getMessage());   
  7.   }   
  8.   
  9.   public void error(SAXParseException e) throws SAXException   
  10.   {   
  11.     System.out.println("[Error ]"+getLocationString(e)+":"+e.getMessage());   
  12.   }   
  13.   
  14.   public void fatalError(SAXParseException e) throws SAXException   
  15.   {   
  16.     System.out.println("[Fatal Error ]"+getLocationString(e)+":"+e.getMessage());   
  17.   }   
  18.   
  19.   private String getLocationString(SAXParseException e)   
  20.   {   
  21.     StringBuffer sb=new StringBuffer();   
  22.     String publicId=e.getPublicId();   
  23.     if(publicId!=null)   
  24.     {   
  25.       sb.append(publicId);   
  26.       sb.append(" ");   
  27.     }   
  28.        
  29.     String systemId=e.getSystemId();   
  30.     if(systemId!=null)   
  31.     {   
  32.       sb.append(systemId);   
  33.       sb.append(" ");   
  34.     }   
  35.        
  36.     sb.append(e.getLineNumber());   
  37.     sb.append(":");   
  38.     sb.append(e.getColumnNumber());   
  39.     return sb.toString();   
  40.   }   
  41. }  
public class ErrorHandlerImpl implements ErrorHandler
{

  public void warning(SAXParseException e) throws SAXException
  {
    System.out.println("[Warning ]"+getLocationString(e)+":"+e.getMessage());
  }

  public void error(SAXParseException e) throws SAXException
  {
    System.out.println("[Error ]"+getLocationString(e)+":"+e.getMessage());
  }

  public void fatalError(SAXParseException e) throws SAXException
  {
    System.out.println("[Fatal Error ]"+getLocationString(e)+":"+e.getMessage());
  }

  private String getLocationString(SAXParseException e)
  {
    StringBuffer sb=new StringBuffer();
    String publicId=e.getPublicId();
    if(publicId!=null)
    {
      sb.append(publicId);
      sb.append(" ");
    }
    
    String systemId=e.getSystemId();
    if(systemId!=null)
    {
      sb.append(systemId);
      sb.append(" ");
    }
    
    sb.append(e.getLineNumber());
    sb.append(":");
    sb.append(e.getColumnNumber());
    return sb.toString();
  }
}

SaxParserTest.java 

Java代码 复制代码
  1. import java.io.FileInputStream;   
  2.   
  3. import org.xml.sax.InputSource;   
  4. import org.xml.sax.XMLReader;   
  5. import org.xml.sax.helpers.XMLReaderFactory;   
  6.   
  7. public class SaxParserTest   
  8. {   
  9.   public static void main(String[] args)   
  10.   {   
  11.     try  
  12.     {   
  13.       XMLReader xmlReader=XMLReaderFactory.createXMLReader();   
  14.       //关闭或打开验证   
  15.       xmlReader.setFeature("http://xml.org/sax/features/validation",true);   
  16.       //注册事件处理器   
  17.       xmlReader.setContentHandler(new ContentHandlerImpl());   
  18.       //注册异常处理器   
  19.       xmlReader.setErrorHandler(new ErrorHandlerImpl());   
  20.          
  21.       xmlReader.parse(new InputSource(new FileInputStream("saxdb.xml")));   
  22.     } catch (Exception e)   
  23.     {   
  24.       System.out.println(e.getMessage());   
  25.     }   
  26.   }   
  27. }  
import java.io.FileInputStream;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;

public class SaxParserTest
{
  public static void main(String[] args)
  {
    try
    {
      XMLReader xmlReader=XMLReaderFactory.createXMLReader();
      //关闭或打开验证
      xmlReader.setFeature("http://xml.org/sax/features/validation",true);
      //注册事件处理器
      xmlReader.setContentHandler(new ContentHandlerImpl());
      //注册异常处理器
      xmlReader.setErrorHandler(new ErrorHandlerImpl());
      
      xmlReader.parse(new InputSource(new FileInputStream("saxdb.xml")));
    } catch (Exception e)
    {
      System.out.println(e.getMessage());
    }
  }
}

第二种:DOM解析
DOM中的核心概念就是节点。DOM在分析XML文档时,将将组成XML文档的各个部分(元素、属性、文本、注释、处理指令等)映射为一个对象(节点)。在内存中,这些节点形成一课文档树。整棵树是一个节点,树中的每一个节点也是一棵树(子树),可以说,DOM就是对这棵树的一个对象描述,我们通过访问树中的节点来存取XML文档的内容。
PS:属性节点是附属于元素的,不能被看做是元素的子节点,更不能作为一个单独的节点

DOMPrinter.java

Java代码 复制代码
  1. import org.w3c.dom.Document;   
  2. import org.w3c.dom.NamedNodeMap;   
  3. import org.w3c.dom.Node;   
  4.   
  5. import com.sun.org.apache.xerces.internal.parsers.DOMParser;   
  6.   
  7. public class DOMPrinter   
  8. {   
  9.   public static void main(String[] args)   
  10.   {   
  11.     try  
  12.     {   
  13.       /** *//** 获取Document对象 */  
  14.       DOMParser parser = new DOMParser();   
  15.       parser.parse("db.xml");   
  16.       Document document = parser.getDocument();   
  17.       printNode(document);   
  18.     } catch (Exception e)   
  19.     {   
  20.       e.printStackTrace();   
  21.     }   
  22.   }   
  23.      
  24.   public static void printNode(Node node)   
  25.   {   
  26.     short nodeType=node.getNodeType();   
  27.     switch(nodeType)   
  28.     {   
  29.     case Node.PROCESSING_INSTRUCTION_NODE://预处理指令类型   
  30.       printNodeInfo(node);   
  31.       break;   
  32.     case Node.ELEMENT_NODE://元素节点类型   
  33.       printNodeInfo(node);   
  34.       printAttribute(node);   
  35.       break;   
  36.     case Node.TEXT_NODE://文本节点类型   
  37.       printNodeInfo(node);   
  38.       break;   
  39.     default:   
  40.       break;   
  41.     }   
  42.        
  43.     Node child=node.getFirstChild();   
  44.     while(child!=null)   
  45.     {   
  46.       printNode(child);   
  47.       child=child.getNextSibling();   
  48.     }   
  49.   }   
  50.      
  51.   /** *//**  
  52.    * 根据节点类型打印节点  
  53.    * @param node  
  54.    */  
  55.   public static void printNodeInfo(Node node)   
  56.   {   
  57.     if (node.getNodeType() == Node.ELEMENT_NODE)   
  58.     {   
  59.       System.out.println("NodeName: " + node.getNodeName());   
  60.     }   
  61.     else if (node.getNodeType() == Node.TEXT_NODE)   
  62.     {   
  63.       String value = node.getNodeValue().trim();   
  64.       if (!value.equals(""))   
  65.         System.out.println("NodeValue: " + value);   
  66.       else  
  67.         System.out.println();   
  68.     }else  
  69.     {   
  70.       System.out.println(node.getNodeName()+" : "+node.getNodeValue());   
  71.     }   
  72.   }   
  73.      
  74.   /** *//**  
  75.    * 打印节点属性  
  76.    * @param aNode 节点  
  77.    */  
  78.   public static void printAttribute(Node aNode)   
  79.   {   
  80.     NamedNodeMap attrs = aNode.getAttributes();   
  81.     if(attrs!=null)   
  82.     {   
  83.       for (int i = 0; i < attrs.getLength(); i++)   
  84.       {   
  85.         Node attNode = attrs.item(i);   
  86.         System.out.println("Attribute: " + attNode.getNodeName() + "=\"" + attNode.getNodeValue()+"\"");   
  87.       }   
  88.     }   
  89.   }  
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

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

public class DOMPrinter
{
  public static void main(String[] args)
  {
    try
    {
      /** *//** 获取Document对象 */
      DOMParser parser = new DOMParser();
      parser.parse("db.xml");
      Document document = parser.getDocument();
      printNode(document);
    } catch (Exception e)
    {
      e.printStackTrace();
    }
  }
  
  public static void printNode(Node node)
  {
    short nodeType=node.getNodeType();
    switch(nodeType)
    {
    case Node.PROCESSING_INSTRUCTION_NODE://预处理指令类型
      printNodeInfo(node);
      break;
    case Node.ELEMENT_NODE://元素节点类型
      printNodeInfo(node);
      printAttribute(node);
      break;
    case Node.TEXT_NODE://文本节点类型
      printNodeInfo(node);
      break;
    default:
      break;
    }
    
    Node child=node.getFirstChild();
    while(child!=null)
    {
      printNode(child);
      child=child.getNextSibling();
    }
  }
  
  /** *//**
   * 根据节点类型打印节点
   * @param node
   */
  public static void printNodeInfo(Node node)
  {
    if (node.getNodeType() == Node.ELEMENT_NODE)
    {
      System.out.println("NodeName: " + node.getNodeName());
    }
    else if (node.getNodeType() == Node.TEXT_NODE)
    {
      String value = node.getNodeValue().trim();
      if (!value.equals(""))
        System.out.println("NodeValue: " + value);
      else
        System.out.println();
    }else
    {
      System.out.println(node.getNodeName()+" : "+node.getNodeValue());
    }
  }
  
  /** *//**
   * 打印节点属性
   * @param aNode 节点
   */
  public static void printAttribute(Node aNode)
  {
    NamedNodeMap attrs = aNode.getAttributes();
    if(attrs!=null)
    {
      for (int i = 0; i < attrs.getLength(); i++)
      {
        Node attNode = attrs.item(i);
        System.out.println("Attribute: " + attNode.getNodeName() + "=\"" + attNode.getNodeValue()+"\"");
      }
    }
  }

DOM生成XML文档:DOMCreateExample.java 

Java代码 复制代码
  1. import java.io.FileNotFoundException;   
  2. import java.io.FileOutputStream;   
  3. import java.io.IOException;   
  4.   
  5. import javax.xml.parsers.DocumentBuilder;   
  6. import javax.xml.parsers.DocumentBuilderFactory;   
  7. import javax.xml.parsers.ParserConfigurationException;   
  8.   
  9. import org.w3c.dom.Document;   
  10. import org.w3c.dom.Element;   
  11.   
  12. import com.sun.org.apache.xml.internal.serialize.XMLSerializer;   
  13.   
  14. pu
package com.hexiang.utils; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; /** * 本类是专门解析XML文件的,主要用于为系统读取自己的配置文件时提供最方便的解析操作 * @author HX * */ public class XmlManager { /** * 得到某节点下某个属性的值 * @param element 要获取属性的节点 * @param attributeName 要取值的属性名称 * @return 要获取的属性的值 * @author HX_2010-01-12 */ public static String getAttribute( Element element, String attributeName ) { return element.getAttribute( attributeName ); } /** * 获取指定节点下的文本 * @param element 要获取文本的节点 * @return 指定节点下的文本 * @author HX_2010-01-12 */ public static String getText( Element element ) { return element.getFirstChild().getNodeValue(); } /** * 解析某个xml文件,并在内存中创建DOM树 * @param xmlFile 要解析XML文件 * @return 解析某个配置文件后的Document * @throws Exception xml文件不存在 */ public static Document parse( String xmlFile ) throws Exception { // 绑定XML文件,建造DOM树 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document domTree = db.parse( xmlFile ); return domTree; } /** * 获得某节点下的某个子节点(指定子节点名称,和某个属性的值) * 即获取parentElement下名字叫childName,并且属性attributeName的值为attributeValue的子结点 * @param parentElement 要获取子节点的那个父节点 * @param childName 要获取的子节点名称 * @param attributeName 要指定的属性名称 * @param attributeValue 要指定的属性的值 * @return 符合条件的子节点 * @throws Exception 子结点不存在或有多个符合条件的子节点 * @author HX_2008-12-01 */ public static Element getChildElement( Element parentElement, String childName, String attributeName, String attributeValue ) throws Exception { NodeList list = parentElement.getElementsByTagName( childName ); int count = 0; Element curElement = null; for ( int i = 0 ; i < list.getLength() ; i ++ ) { Element child = ( Element )list.item( i ); String value = child.getAttribute( attributeName ); if ( true == value.equals( attributeValue ) ) { curElement =
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值