zoukankan      html  css  js  c++  java
  • 应用dom4j读取xml的例子

    1. 样例xml

    <?xml version="1.0" encoding="UTF-8"?>
    <students>
        <student>
            <name type="String">aaa</name>
            <age  type="int">22</age>
        </student>
        <student>
            <name type="String">bbb</name>
            <age  type="int">23</age>
        </student>
        <student>
            <name type="String">ccc</name>
            <age  type="int">21</age>
        </student>
    </students>
    

    2. 读入各种形式的xml

    2.1 读入文件

    	SAXReader reader = new SAXReader();
    	Document document = reader.read(new File("d:/tmp/3.xml"));
    

    2.2 读入文件内容(字符串)

    String text = "<?xml version="1.0" encoding="UTF-8"?><students>    <student>        <name type="String">aaa</name>        <age  type="int">22</age>    </student>    <student>        <name type="String">bbb</name>        <age  type="int">23</age>    </student>    <student>        <name type="String">ccc</name>        <age  type="int">21</age>    </student></students>";
    
    Document document = DocumentHelper.parseText(text);
    

    2.3 读入网络URL

    	String url = "http://www.webservicex.net/globalweather.asmx?wsdl";
    	SAXReader reader = new SAXReader();
    	URL realUrl = new URL(url);
    	Document document = reader.read(realUrl);
    

    3. 获得节点与属性

    在得到document之后,可以得到该xml的所有节点与属性。

    		Element rootElement = document.getRootElement();
    		if (rootElement == null) {
    			return "";
    		}
    		Element se = rootElement.element("types");
    		if (se == null) {
    			return "";
    		}
    		Element se1 = se.element("schema");
    		if (se1 == null) {
    			return "";
    		}
    		Element se2 = se1.element("element");
    		if (se2 == null) {
    			return "";
    		}
    		return se2.attributeValue("name");
    
  • 相关阅读:
    c++ range库
    差分数组
    简单比较一下C++中的引用和指针
    数字图像处理中一张常用图片
    内存池与内存块
    SmartPtr
    Allocator
    Java学习第12天
    Java学习第11天
    Java学习第10天
  • 原文地址:https://www.cnblogs.com/wardensky/p/4749826.html
Copyright © 2011-2022 走看看