使用DOM解析简单的XML文档实例

快速理解使用DOM解析简单的XML文档介绍了在使用DOM解析XML文档时最重要和常用的就是Element节点和Text节点,下面的实例就是用ant的配置文件和maven的配置文件来解析其中的jar包。

import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
 
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
 
public class DomExample
{
         private static final String ANT = "E:\\trayvon\\note\\server.xml";
         private static final String POM = "E:\\trayvon\\note\\pom.xml";
         public static void main(String[] args)
         {
                   extractJarFromAnt();
                   extractJarFromMaven();
         }
        
         public static void extractJarFromMaven()
         {
                   Document doc = initDocument(POM);
//               Element root = doc.getDocumentElement();//取全部
                   Element root = (Element) doc.getElementsByTagName("dependencies").item(0);//只取dependencies所代表的节点
                   dealPomElement(root);
                  
         }
         public static void dealPomElement(Element ele)
         {
                   NodeList childNodes = ele.getChildNodes();
                   for(int i=0;i<childNodes.getLength();i++)
                   {
                            Node node = childNodes.item(i);
                            if(node.getNodeType()==Node.ELEMENT_NODE)
                            {
                                     Element e = (Element)node;
                                     if(node.getNodeName().equals("artifactId"))
                                     {
                                               Node text = node.getFirstChild();//获取Element节点artifactId下面的Text节点
                                               System.out.println(text.getNodeValue()+".jar");//Text节点的nodeValue就是其值
                                     }
                                     dealPomElement(e);
                            }
                   }
         }
         public static void extractJarFromAnt()
         {
                   Document doc = initDocument(ANT);
                   Element root = doc.getDocumentElement();
                   dealAntElement(root);
         }
         private static void dealAntElement(Element ele)
         {
                   NodeList childNodes = ele.getChildNodes();
                   for(int i=0;i<childNodes.getLength();i++)
                   {
                            Node node = childNodes.item(i);
                            if(node.getNodeType()==Node.ELEMENT_NODE)
                            {
                                     Element e = (Element)node;
                                     if(node.getNodeName().equals("pathelement"))
                                     {
                                               String jar = e.getAttribute("location");
                                               System.out.println(jar.substring(jar.lastIndexOf('/')+1));
                                     }
                                     if(e.getNodeName().equals("include"))
                                     {
                                               System.out.println(e.getAttribute("name"));
                                     }
                                     dealAntElement(e);//根据情况选择是否递归,已经知道节点的名称了可以使用NodeList org.w3c.dom.Document.getElementsByTagName(String tagname)方法
                            }
                   }
         }
         private static Document initDocument(String xml)
         {
                   DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                   DocumentBuilder builder = null;
                   Document doc = null;
                   try
                   {
                            builder = factory.newDocumentBuilder();
                   } catch (ParserConfigurationException e)
                   {
                            e.printStackTrace();
                   }
                   try
                   {
                            doc = builder.parse(xml);
                   } catch (SAXException | IOException e)
                   {
                            e.printStackTrace();
                   }
                   return doc;
         }
}

 

其中server.xml的类容如下:

<?xml version="1.0"?>
<project basedir="../" name="forumserver" default="rebuild">
  <property environment="env"/>
  <property name="dest" value="dist/server" />
  <property name="src" value="src/server"/>
  <property name="bin" value="bin"/>
  <property name="client" value="src/client"/>
  <property name="common" value="src/common"/>
 
  <property name="Log4j.Home" value="${env.LOG4J_HOME}"/>
  <property name="YupCommon.Home" value="${env.YUPCOMMON_HOME}"/>
  <property name="YupLib.Home" value="${env.YUPLIB_HOME}"/>
  <property name="Jtds.Home" value="${env.JTDS_HOME}"/>
  <property name="Lucene.Home" value="${env.LUCENE3_HOME}"/>
  <property name="Paoding.Analyzer.Home" value="${env.PAODING3_ANALYZER_HOME}"/>
  <property name="Spring.Home" value="${env.SPRING_HOME}"/>
  <property name="MYSQL.home" value="${env.MYSQL_HOME}"/>
  <property name="Jdom.Home" value="${env.JDOM_HOME}"/>
  <property name="Apache.Common.Home" value="${env.APACHE_COMMON_HOME}"/>
  <property name="ibatis.home" value="${env.IBATIS_HOME}"/>
  <property name="activemq.home" value="${env.ACTIVEMQ_HOME}"/>
  <property name="jms.home" value="${env.JMS_HOME}"/>
  <property name="JavaMemcachedClient.Home" value="${env.JAVA_MEMCACHED_CLIENT_HOME}" />
  <property name="pinyin4j.home" value="${env.PINYIN4J_HOME}"/>
  <property name="aop.home" value="${env.AOP_HOME}"/>
  <property name="HTMLPARSER_HOME.home" value="${env.HTMLPARSER_HOME}"/>
  <property name="Mongo.home" value="${env.MONGO_HOME}"/>
  <property name="json.home" value="${env.JSON_HOME}"/>
  <property name="aspectj.home" value="${env.ASPECTJ_HOME}"/>
 
  <path id="project.class.path">
    <pathelement location="${Log4j.Home}/log4j-1.2.8.jar"/>
    <pathelement location="${YupCommon.Home}/yupcommon.jar"/>
    <pathelement location="${YupLib.Home}/yuplib.jar"/>
    <pathelement location="${Jtds.Home}/jtds-1.2.2.jar"/>
    <pathelement location="${Lucene.Home}/lucene-core-3.0.3.jar"/>
    <pathelement location="${Lucene.Home}/contrib/analyzers/common/lucene-analyzers-3.0.3.jar"/>
    <pathelement location="${Paoding.Analyzer.Home}/paoding-analysis.jar"/>
    <pathelement location="${Spring.Home}/dist/spring.jar"/>
    <pathelement location="${Spring.Home}/lib/jakarta-commons/commons-dbcp.jar"/>
    <pathelement location="${Spring.Home}/lib/jakarta-commons/commons-pool.jar"/>
    <pathelement location="${Spring.Home}/lib/jakarta-commons/commons-logging.jar"/>
    <pathelement location="${MYSQL.home}/mysql-connector-java-5.1.31-bin.jar"/>
    <pathelement location="${Jdom.Home}/build/jdom.jar"/>
    <pathelement location="${Jdom.Home}/lib/jaxen-core.jar"/>
    <pathelement location="${Jdom.Home}/lib/jaxen-jdom.jar"/>
    <pathelement location="${Jdom.Home}/lib/saxpath.jar"/>
    <pathelement location="${Jdom.Home}/lib/xalan.jar"/>
    <pathelement location="${Jdom.Home}/lib/xerces.jar"/>
    <pathelement location="${Apache.Common.Home}/commons-dbcp-1.2.1.jar"/>
    <pathelement location="${Apache.Common.Home}/commons-pool-1.2.jar"/>
    <pathelement location="${Apache.Common.Home}/commons-logging.jar"/>
    <pathelement location="${Apache.Common.Home}/commons-collections-3.1.jar"/>
    <pathelement location="${ibatis.home}/lib/ibatis-2.3.4.726.jar"/>
    <pathelement location="${jms.home}/javax.jms.jar"/>
    <pathelement location="${pinyin4j.home}/lib/pinyin4j-2.5.0.jar"/>
    <pathelement location="${aop.home}/cglib-nodep-2.1_3.jar"/>
    <pathelement location="${activemq.home}/geronimo-j2ee-management_1.1_spec-1.0.1.jar"/>
    <pathelement location="${activemq.home}/activemq-core-5.4.0.jar"/>
    <pathelement location="${activemq.home}/activemq-pool-5.4.0.jar"/>
    <pathelement location="${JavaMemcachedClient.Home}/memcached-2.5.jar" />
 
  <pathelement location="${HTMLPARSER_HOME.home}/htmlparser.jar"/>
  <pathelement location="${Mongo.home}/mongo-2.10.1.jar"/>
  <pathelement location="${json.home}/json-20131018.jar"/>
    <pathelement location="${aspectj.home}/aspectj-1.6.12.jar"/>
    <pathelement location="${aspectj.home}/aspectjweaver-1.5.2.jar"/>
 
  </path>
 
  <target name="rebuild" depends="jar-common,jar">
    <copy todir="${dest}">
     <fileset dir="${Log4j.Home}">
        <filename name="log4j-1.2.8.jar"/>
      </fileset>
      <fileset dir="${YupCommon.Home}">
        <filename name="yupcommon.jar"/>
      </fileset>
      <fileset dir="${YupLib.Home}">
        <filename name="yuplib.jar"/>
      </fileset>
      <fileset dir="${Jtds.Home}">
        <filename name="jtds-1.2.2.jar"/>
      </fileset>
      <fileset dir="${Spring.Home}">
        <include name="spring.jar"/>
      </fileset>
      <fileset dir="${rmi.client.home}">
        <include name="rmiclib.jar"/>
      </fileset>
      <fileset dir="${Jdom.Home}/build">
        <filename name="jdom.jar"/>
      </fileset>
      <fileset dir="${Jdom.Home}/lib">
        <include name="jaxen-core.jar"/>
        <include name="jaxen-jdom.jar"/>
        <include name="saxpath.jar"/>
        <include name="xalan.jar"/>
        <include name="xerces.jar"/>
      </fileset>
      <fileset dir="${Spring.Home}/lib/jakarta-commons/">
        <filename name="commons-logging.jar"/>
      </fileset>
 
      <fileset dir="${Apache.Common.Home}">
        <include name="commons-dbcp-1.2.1.jar"/>
        <include name="commons-pool-1.2.jar"/>
        <include name="commons-logging.jar"/>
        <include name="commons-collections-3.1.jar"/>
      </fileset>
      <fileset dir="${activemq.home}">
        <include name="activemq-pool-5.4.0.jar"/>
        <include name="activemq-core-5.4.0.jar"/>
        <include name="geronimo-j2ee-management_1.1_spec-1.0.1.jar"/>
      </fileset>
      <fileset dir="${jms.home}">
       <include name="javax.jms.jar"/>
      </fileset>
     
      <fileset dir="${ibatis.home}/lib">
       <include name="ibatis-2.3.4.726.jar"/>
      </fileset>
       <fileset dir="${JavaMemcachedClient.Home}">
        <filename name="memcached-2.5.jar" />
      </fileset>
      <fileset dir="${pinyin4j.home}/lib">
        <filename name="pinyin4j-2.5.0.jar"/>
       </fileset>
    <fileset dir="${aop.home}">
        <include name="cglib-nodep-2.1_3.jar"/>
       </fileset>
    <fileset dir="${Lucene.Home}">
    <include name="lucene-core-3.0.3.jar"/>
    </fileset>
    <fileset dir="${Lucene.Home}/contrib/analyzers/common/">
    <include name="lucene-analyzers-3.0.3.jar"/>
    </fileset>
      <fileset dir="${Paoding.Analyzer.Home}">
      <include name="paoding-analysis.jar"/>
      </fileset>
      <fileset dir="${MYSQL.home}">
      <filename name="mysql-connector-java-5.1.31-bin.jar"/>
      </fileset>
    
     
      <fileset dir="${HTMLPARSER_HOME.home}">
       <include name="htmlparser.jar" />
      </fileset>
    
            
             <fileset dir="${Mongo.home}">
                       <include name="mongo-2.10.1.jar" />
             </fileset>
             <fileset dir="${json.home}">
                                    <include name="json-20131018.jar" />
                </fileset>
        <fileset dir="${aspectj.home}">
                 <include name="aspectj-1.6.12.jar"/>
          <include name="aspectjweaver-1.5.2.jar"/>
        </fileset>
    </copy>
  </target>
 
  <target name="compile" depends="init">
    <javac destdir="${bin}" classpathref="project.class.path" source="1.5" target="1.5" encoding="utf-8">
      <src path="${src}"/>
      <src path="${common}"/>
    </javac>
  </target>
 
  <target name="init" depends="cleanup">
    <mkdir dir="${dest}"/>
    <mkdir dir="${bin}"/>
    <echo>${Spring.Home}/lib/jakarta-commons/</echo>
    <echo>${Jdom.Home}</echo>
  </target>
</project>

pom.xml的类容如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>base</artifactId>
        <groupId>com.freemethod</groupId>
        <version>1.0.0</version>
        <relativePath>../cd-base/pom.xml</relativePath>
    </parent>
 
    <modelVersion>4.0.0</modelVersion>
    <groupId>cn.freemethod.app.backend</groupId>
    <artifactId>dcd-smtpfbackend</artifactId>
    <version>1.2.62-RELEASE</version>
    <packaging>war</packaging>
    <url>http://freemethod.cn:8080</url>
 
    <dependencies>
        <!-- spring framework dependency -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc-portlet</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-asm</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-instrument</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-instrument-tomcat</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>
 
        <!-- quartz -->
        <dependency>
            <groupId>opensymphony</groupId>
            <artifactId>quartz-all</artifactId>
        </dependency>
 
        <!-- MyBatis -->
        <dependency>
            <groupId>org.apache.ibatis</groupId>
            <artifactId>ibatis-sqlmap</artifactId>
        </dependency>
 
        <!-- MySQL JDBC Driver -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
 
        <!-- DB Pool-->
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
        </dependency>
 
        <!-- apache commons -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-pool</groupId>
            <artifactId>commons-pool</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-digester</groupId>
            <artifactId>commons-digester</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-httpclient</groupId>
            <artifactId>commons-httpclient</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-net</groupId>
            <artifactId>commons-net</artifactId>
        </dependency>
 
        <!-- Jdom -->
        <dependency>
            <groupId>jdom</groupId>
            <artifactId>jdom</artifactId>
        </dependency>
        <dependency>
            <groupId>org.jdom</groupId>
            <artifactId>jaxen-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.jdom</groupId>
            <artifactId>jaxen-jdom</artifactId>
        </dependency>
        <dependency>
            <groupId>org.jdom</groupId>
            <artifactId>saxpath</artifactId>
        </dependency>
 
        <!-- logger4j -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
        </dependency>
 
        <!-- jms -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jms</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.geronimo.specs</groupId>
            <artifactId>geronimo-jms_1.1_spec</artifactId>
        </dependency>
 
        <dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-pool</artifactId>
            <version>5.10.0</version>
        </dependency>
 
        <dependency>
            <groupId>net.sourceforge.jtds</groupId>
            <artifactId>jtds</artifactId>
        </dependency>
 
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-core-lgpl</artifactId>
        </dependency>
 
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-core-asl</artifactId>
        </dependency>
 
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-lgpl</artifactId>
        </dependency>
 
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
        </dependency>
 
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
 
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
        </dependency>
            <dependency> 
        <groupId>javax.servlet</groupId> 
        <artifactId>javax.servlet-api</artifactId> 
        <version>3.0.1</version> 
    </dependency> 
 
        <!-- junit dependency -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>
 
        <dependency>
            <groupId>com.caucho</groupId>
            <artifactId>hessian</artifactId>
        </dependency>
 
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
        </dependency>
 
        <dependency>
            <groupId>net.sf.ezmorph</groupId>
            <artifactId>ezmorph</artifactId>
            <version>1.0.6</version>
        </dependency>
 
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.0.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.0.3</version>
        </dependency>
 
        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <classifier>jdk15</classifier>
        </dependency>
 
        <dependency>
            <groupId>jexcelapi</groupId>
            <artifactId>jxl</artifactId>
            <version>2.4.2</version>
        </dependency>
 
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.0</version>
        </dependency>
 
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.1.26</version>
        </dependency>
 
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>17.0</version>
        </dependency>
 
                  
          <!-- mongdb drive start -->
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
            <version>2.13.0</version>
        </dependency>
        <!-- mongdb drive end -->
        <!-- morphia start -->
        <dependency>
            <groupId>org.mongodb.morphia</groupId>
            <artifactId>morphia</artifactId>
            <version>0.111</version>
        </dependency>
        <dependency>
            <groupId>org.mongodb.morphia</groupId>
            <artifactId>morphia-logging-slf4j</artifactId>
            <version>0.111</version>
        </dependency>
        <!-- morphia end -->
      
                  
 
                   <dependency>
            <groupId>org.apache.lucene</groupId>
            <artifactId>lucene-core</artifactId>
            <version>4.7.2</version>
        </dependency>
       <dependency>
                     <groupId>jce</groupId>
                     <artifactId>jce</artifactId>
                     <version>1.6</version>
                      <scope>compile</scope>
                   </dependency>
        <dependency>
            <groupId>rt</groupId>
            <artifactId>rt</artifactId>
            <version>1.6</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>
 
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <configuration>
                    <warName>backend2</warName>
                    <archiveClasses>false</archiveClasses>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-scm-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-release-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>


你可能感兴趣的:(xml,element,dom,xml解析,XML解析实例)