Dom4j解析Xml文件,Dom4j创建Xml文件


Dom4j解析Xml文件,Dom4j创建Xml文件

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

蕃薯耀 2016年3月1日 10:54:34 星期二

http://fanshuyao.iteye.com/

一、引入Jar包

dom4j-1.6.1.jar

二、详细代码

package com.lqy.dom4j;

import java.io.File;
import java.io.FileWriter;
import java.util.Iterator;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class Dom4jTest {

	
	public static void main(String[] args) throws Exception {
		//createXml();
		//createXml2();
		readXml1();
	}
	
	private static void createXml() throws Exception{
		Document document = DocumentHelper.createDocument();
		Element rootElement = document.addElement("students");
		
		Element studentElement = rootElement.addElement("student");
		studentElement.addAttribute("id", "s001");
		studentElement.addAttribute("xx", "xx001");
		studentElement.addElement("name").addText("张三");
		studentElement.addElement("age").addText("20");
		
		Element studentElement1 = rootElement.addElement("student");
		studentElement1.addAttribute("id", "s002");
		studentElement1.addAttribute("xx", "xx002");
		studentElement1.addElement("name").addText("李四");
		studentElement1.addElement("age").addText("21");
		
		XMLWriter xmlWriter = new XMLWriter(new FileWriter("src/student.xml"));
		xmlWriter.write(rootElement);
		xmlWriter.close();
		System.out.println("执行完成了!");
	}
	
	private static void createXml2() throws Exception{
		Document document = DocumentHelper.createDocument();
		Element rootElement = document.addElement("students");
		
		Element stu1 = rootElement.addElement("student");
		stu1.addAttribute("id", "s001");
		stu1.addAttribute("xx", "xx001");
		stu1.addElement("name").addText("张三");
		stu1.addElement("age").addText("20");
		
		Element stu2 = rootElement.addElement("student");
		stu2.addAttribute("id", "s002");
		stu2.addAttribute("xx", "xx002");
		stu2.addElement("name").addText("李四");
		stu2.addElement("age").addText("21");
		
		OutputFormat outputFormat = OutputFormat.createPrettyPrint();
		XMLWriter xmlWriter = new XMLWriter( System.out, outputFormat);
		xmlWriter.write( document );
		xmlWriter.close();
		System.out.println("执行完成了!");
	}
	
	
	private static void readXml1() throws Exception{
		SAXReader saxReader = new SAXReader();
		Document document = saxReader.read(new File("src/student.xml"));
		if(document != null){
			Element root = document.getRootElement();
			if(root != null){
				Iterator<Element> iterator = root.elementIterator();
				while(iterator.hasNext()){
					Element e = iterator.next();
					System.out.println("学生信息:");
					System.out.println("学生id:"+e.attributeValue("id"));
					System.out.println("学生xx:"+e.attributeValue("xx"));
					System.out.println("学生姓名:"+e.elementText("name"));
					System.out.println("学生年龄:"+e.elementText("age"));
					System.out.println("==========================");
				}
			}
		}
	}
}

三、官网文档:

Parsing XML

One of the first things you'll probably want to do is to parse an XML document of some kind. This is easy to do indom4j. The following code demonstrates how to this.

import java.net.URL;

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

public class Foo {

    public Document parse(URL url) throws DocumentException {
        SAXReader reader = new SAXReader();
        Document document = reader.read(url);
        return document;
    }
}

Using Iterators

A document can be navigated using a variety of methods that return standard Java Iterators. For example

    public void bar(Document document) throws DocumentException {

        Element root = document.getRootElement();

        // iterate through child elements of root
        for ( Iterator i = root.elementIterator(); i.hasNext(); ) {
            Element element = (Element) i.next();
            // do something
        }

        // iterate through child elements of root with element name "foo"
        for ( Iterator i = root.elementIterator( "foo" ); i.hasNext(); ) {
            Element foo = (Element) i.next();
            // do something
        }

        // iterate through attributes of root 
        for ( Iterator i = root.attributeIterator(); i.hasNext(); ) {
            Attribute attribute = (Attribute) i.next();
            // do something
        }
     }

Powerful Navigation with XPath

Indom4jXPath expressions can be evaluated on the Document or on any Node in the tree (such as Attribute, Element or ProcessingInstruction). This allows complex navigation throughout the document with a single line of code. For example.

    public void bar(Document document) {
        List list = document.selectNodes( "//foo/bar" );

        Node node = document.selectSingleNode( "//foo/bar/author" );

        String name = node.valueOf( "@name" );
    }

For example if you wish to find all the hypertext links in an XHTML document the following code would do the trick.

    public void findLinks(Document document) throws DocumentException {

        List list = document.selectNodes( "//a/@href" );

        for (Iterator iter = list.iterator(); iter.hasNext(); ) {
            Attribute attribute = (Attribute) iter.next();
            String url = attribute.getValue();
        }
    }

If you need any help learning the XPath language we highly recommend theZvon tutorialwhich allows you to learn by example.

Fast Looping

If you ever have to walk a large XML document tree then for performance we recommend you use the fast looping method which avoids the cost of creating an Iterator object for each loop. For example

    public void treeWalk(Document document) {
        treeWalk( document.getRootElement() );
    }

    public void treeWalk(Element element) {
        for ( int i = 0, size = element.nodeCount(); i < size; i++ ) {
            Node node = element.node(i);
            if ( node instanceof Element ) {
                treeWalk( (Element) node );
            }
            else {
                // do something....
            }
        }
    }

Creating a new XML document

Often indom4jyou will need to create a new document from scratch. Here's an example of doing that.

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

public class Foo {

    public Document createDocument() {
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement( "root" );

        Element author1 = root.addElement( "author" )
            .addAttribute( "name", "James" )
            .addAttribute( "location", "UK" )
            .addText( "James Strachan" );
        
        Element author2 = root.addElement( "author" )
            .addAttribute( "name", "Bob" )
            .addAttribute( "location", "US" )
            .addText( "Bob McWhirter" );

        return document;
    }
}

Writing a document to a file

A quick and easy way to write a Document (or any Node) to a Writer is via the write() method.

  FileWriter out = new FileWriter( "foo.xml" );
  document.write( out );

If you want to be able to change the format of the output, such as pretty printing or a compact format, or you want to be able to work with Writer objects or OutputStream objects as the destination, then you can use the XMLWriter class.

import org.dom4j.Document;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

public class Foo {

    public void write(Document document) throws IOException {

        // lets write to a file
        XMLWriter writer = new XMLWriter(
            new FileWriter( "output.xml" )
        );
        writer.write( document );
        writer.close();


        // Pretty print the document to System.out
        OutputFormat format = OutputFormat.createPrettyPrint();
        writer = new XMLWriter( System.out, format );
        writer.write( document );

        // Compact format to System.out
        format = OutputFormat.createCompactFormat();
        writer = new XMLWriter( System.out, format );
        writer.write( document );
    }
}

Converting to and from Strings

If you have a reference to a Document or any other Node such as an Attribute or Element, you can turn it into the default XML text via the asXML() method.

        Document document = ...;
        String text = document.asXML();

If you have some XML as a String you can parse it back into a Document again using the helper method DocumentHelper.parseText()

        String text = "<person> <name>James</name> </person>";
        Document document = DocumentHelper.parseText(text);

Styling a Document with XSLT

Applying XSLT on a Document is quite straightforward using theJAXPAPI from Sun. This allows you to work against any XSLT engine such as Xalan or SAXON. Here is an example of using JAXP to create a transformer and then applying it to a Document.

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;

import org.dom4j.Document;
import org.dom4j.io.DocumentResult;
import org.dom4j.io.DocumentSource;

public class Foo {

    public Document styleDocument(
        Document document, 
        String stylesheet
    ) throws Exception {

        // load the transformer using JAXP
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer( 
            new StreamSource( stylesheet ) 
        );

        // now lets style the given document
        DocumentSource source = new DocumentSource( document );
        DocumentResult result = new DocumentResult();
        transformer.transform( source, result );

        // return the transformed document
        Document transformedDoc = result.getDocument();
        return transformedDoc;
    }
}

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

蕃薯耀 2016年3月1日 10:54:34 星期二

http://fanshuyao.iteye.com/

优质内容筛选与推荐>>
1、拒绝访问。 (异常来自 HRESULT:0x80070005 (E_ACCESSDENIED)) 使用Enterprise Library 3.0的磁盘缓存Isolated Storage 的问题
2、GridView绑定多个参数值
3、实现临界区互斥的基本方法
4、序列的第k个数
5、ORACLE触发器详解


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号





    联系我们

    欢迎来到TinyMind。

    关于TinyMind的内容或商务合作、网站建议,举报不良信息等均可联系我们。

    TinyMind客服邮箱:support@tinymind.net.cn