当前位置: 首页 > 工具软件 > Dom4g > 使用案例 >

org.dom4j.io.SAXReader解析xml

倪炎彬
2023-12-01

参考网址

XPath 语法
http://www.w3school.com.cn/xpath/xpath_syntax.asp

XML文件

G:\eclipsewk\SDK201702\Test-Pack\package\work\before\AndroidManifest.xml

<?xml version="1.0" encoding="UTF-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.android.test" 
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.GET_TASKS" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />

    <application>
        <activity
            android:name="com.android.test.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service android:name="com.android.test.CoreService"
            android:exported="true" >
        </service>
    </application>

</manifest>

解析代码

Element org.dom4j.Document.getRootElement()

InputStream fis=new FileInputStream("G:\\eclipsewk\\SDK201702\\Test-Pack\\package\\work\\before\\AndroidManifest.xml");
Document document = new SAXReader().read(fis);// 得到Document对象
Element root = document.getRootElement();// 获得根节点
System.out.println("-----------------root----------------");
System.out.println(root.asXML());//打印出整个xml文件的内容
打印的结果是:
-----------------root----------------
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.android.test" android:versionCode="1" android:versionName="1.0">

    <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="21"/>

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.GET_TASKS"/>
    <uses-permission android:name="android.permission.WAKE_LOCK"/>

    <application>
        <activity android:name="com.android.test.MainActivity" android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>

        <service android:name="com.android.test.CoreService"
            android:exported="true" >
        </service>
    </application>

</manifest>

Attribute org.dom4j.Element.attribute(String paramString)

String attribute=root.attribute("package").getText();//获取一个attribute的值
System.out.println("-----------------package----------------"+attribute);

/***打印结果:
-----------------package----------------com.android.test
*/
String attribute=root.attribute("application").getText();//会报错java.lang.NullPointerException
System.out.println("-----------------application----------------"+attribute);

/***打印结果:
java.lang.NullPointerException
    at pack.SAXReaderXML.main(SAXReaderXML.java:...)
*/

Node org.dom4j.Node.selectSingleNode(String paramString)

Element element = (Element)root.selectSingleNode("//application");
System.out.println("----selectSingleNode application ----");
System.out.println("application "+element.asXML());

/***打印结果:
----selectSingleNode application ----
application <application>
        <activity xmlns:android="http://schemas.android.com/apk/res/android" 
            android:name="com.android.test.MainActivity" 
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>

        <service android:name="com.android.test.CoreService"
            android:exported="true" >
        </service>
</application>

*/
/**再来看一个例子
//表示从匹配选择的当前节点选择文档中的节点,而不考虑它们的位置**/
Element element = (Element)root.selectSingleNode("//application//activity//intent-filter");
System.out.println(element.asXML());

/***打印结果:
<intent-filter>
       <action xmlns:android="http://schemas.android.com/apk/res/android" 
       android:name="android.intent.action.MAIN"/>

      <category xmlns:android="http://schemas.android.com/apk/res/android" 
      android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
*/

List org.dom4j.Node.selectNodes(String paramString)

System.out.println("----selectNodes uses-permission ----");
List<?> nodesList = root.selectNodes("//uses-permission");
for (int i = 0; i < nodesList.size(); i++) {
    System.out.println("-----node------"+i);
    Element node = (Element)nodesList.get(i);
    System.out.println(node.asXML());
}

/***打印结果:
----selectNodes uses-permission ----
-----node------0
<uses-permission xmlns:android="http://schemas.android.com/apk/res/android"         
android:name="android.permission.ACCESS_NETWORK_STATE"/>
-----node------1
<uses-permission xmlns:android="http://schemas.android.com/apk/res/android" android:name="android.permission.GET_TASKS"/>
-----node------2
<uses-permission xmlns:android="http://schemas.android.com/apk/res/android" android:name="android.permission.WAKE_LOCK"/>
*/

Iterator org.dom4j.Element.elementIterator()

System.out.println("---------Iterator org.dom4j.Element.elementIterator()-----------");
Element element = (Element)root.selectSingleNode("//application");
Iterator iterator=element.elementIterator();//再从子节点在遍历其子节点
while (iterator.hasNext()) {
    Element next = (Element) iterator.next();
    System.out.println("---------next.asXML-----------");
    System.out.println(next.asXML());
}

/***打印结果:
---------Iterator org.dom4j.Element.elementIterator()-----------
---------next.asXML-----------
<activity xmlns:android="http://schemas.android.com/apk/res/android" 
    android:name="com.android.test.MainActivity" 
    android:label="@string/app_name">
           <intent-filter>
               <action android:name="android.intent.action.MAIN"/>

               <category android:name="android.intent.category.LAUNCHER"/>
           </intent-filter>
</activity>
---------next.asXML-----------
<service xmlns:android="http://schemas.android.com/apk/res/android"
    android:name="com.android.test.CoreService" 
    android:exported="true">
</service>
*/

全部代码

package pack;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Iterator;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class SAXReaderXML {
    public static void main(String[] args) {
        try {
            InputStream fis=new FileInputStream("G:\\eclipsewk\\SDK201702\\Test-
            Pack\\package\\work\\before\\AndroidManifest.xml");//
            Document document = new SAXReader().read(fis);// 得到Document对象
            Element root = document.getRootElement();// 获得根节点
//          System.out.println("-----------------root----------------");
//          System.out.println(root.asXML());

//          String attribute=root.attribute("package").getText();
//          System.out.println("-----------------package----------------"+attribute);

//          String attribute=root.attribute("application").getText();//java.lang.NullPointerException
//          System.out.println("-----------------application----------------"+attribute);
//          

//          Element element = (Element)root.selectSingleNode("//application");
//          System.out.println("----selectSingleNode application ----");
//          System.out.println("application "+element.asXML());

//          Element element = (Element)root.selectSingleNode("//application//activity//intent-
            filter");
//          System.out.println(element.asXML());


//          System.out.println("----selectNodes uses-permission ----");
//          List<?> nodesList = root.selectNodes("//uses-permission");
//          for (int i = 0; i < nodesList.size(); i++) {
//              System.out.println("-----node------"+i);
//              Element node = (Element)nodesList.get(i);
//              System.out.println(node.asXML());
//          }


//          System.out.println("---------Iterator org.dom4j.Element.elementIterator()-----------");
//          Element element = (Element)root.selectSingleNode("//application");
//          Iterator iterator=element.elementIterator();//再从子节点在遍历其子节点
//          while (iterator.hasNext()) {
//              Element next = (Element) iterator.next();
//              System.out.println("---------next.asXML-----------");
//              System.out.println(next.asXML());
//          }

            System.out.println("---------Iterator org.dom4j.Element.elementIterator()---------
            --");
            Element element = (Element)root.selectSingleNode("//application");
            Iterator iterator=element.elementIterator();//再从子节点在遍历其子节点
            while (iterator.hasNext()) {
                Element next = (Element) iterator.next();
                System.out.println("---------next.asXML-----------");
                System.out.println(next.asXML());
                System.out.println("---------next getName-----------");
                System.out.println(next.getName());
                System.out.println("---------next getText-----------");
                System.out.println(next.getText());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Node、Element、Attribute

<?xml version="1.0" encoding="ISO-8859-1"?>
<bookstore>
    <book>
      <title lang="eng">Harry Potter</title>
      <price>29.99</price>
    </book>
</bookstore>

/**
1、想要获取title 的名字怎么做?
2、想要获取lang="eng"这个名字和对应的值怎么做?
3、想要获取39.95这个值怎么做?
*/
package pack;

import java.io.FileInputStream;
import java.io.InputStream;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class SAXReaderXML2 {
    public static void main(String[] args) {
        try {
            InputStream fis=new FileInputStream("G:\\eclipsewk\\SDK201702\\Test-Pack\\package\\work\\before\\bookstore.xml");//
            Document document = new SAXReader().read(fis);// 得到Document对象
            Element root = document.getRootElement();// 获得根节点

            Element titleElement = (Element)root.selectSingleNode("//book//title");
            System.out.println("---------titleElement asXML-----------");
            System.out.println(titleElement.asXML());

            Attribute attribute=titleElement.attribute("lang");
            System.out.println("-----String org.dom4j.Node.getName()--"+attribute.getName());
            System.out.println("-----String org.dom4j.Node.getValue()--"+attribute.getValue());


            Element priceElement = (Element)root.selectSingleNode("//book//price");
            System.out.println("---------String org.dom4j.Node.asXML()-----------");
            System.out.println(priceElement.asXML());
            System.out.println("-----String org.dom4j.Node.getName()--"+priceElement.getName());
            System.out.println("-----String org.dom4j.Element.getText()--"+priceElement.getText());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

总结

1、Element和Node是什么关系?

先看org.dom4j.Element的定义
public abstract interface Element  extends Branch

再看org.dom4j.Branch的定义
public abstract interface Branch  extends Node

2、Element和Attribute是什么关系?

先看org.dom4j.Attribute的定义
public abstract interface Attribute  extends Node

从Element中获取Attribute怎么做
Attribute org.dom4j.Element.attribute(String paramString)

3、XML文件和Element是什么关系?

XML文件由多个Element构成。每一个Element下面可以有多个子Element
4、Element长什么样子

    <ParentElementgetName>
        <ChildElementgetName 
            AttributegetName="AttributegetValue">
                ChildElementgetText
        </ChildElementgetName>
    </ParentElementgetName>

看到这个你get到String org.dom4j.Node.getName()、String org.dom4j.Element.getText()、String org.dom4j.Node.getValue()三个函数的用法了吗?
 类似资料: