dom4j對xml的解析

首先我們來看一下dom4j的官方文檔,這是最好的方法!

PARSING XML (解析 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 in dom4j. The following code demonstrates how to this.

第一件事情,你可能就是想去解析一個xml文檔,這是容易的對於dom4j來說。下面的實例就是展示給我們怎麼樣去做!

try {
			//創建一個讀取器
			SAXReader reader = new SAXReader();
			//讀取一個xml文檔
			Document d = reader.read("src/book.xml");
			
			System.out.println("result:"+d.toString());
		} catch (DocumentException e) {
			throw new RuntimeException(e);
		}

USING ITERATORS(運用迭代)

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

一個文檔可以被操縱用多種方法並且返回一個標準的java迭代器!例如:

//獲得一個根節點
			Element root = d.getRootElement();
			
			//迭代出根節點的屬性,用到了屬性迭代器!
			for(Iterator<Attribute> it = root.attributeIterator();it.hasNext();)
			{
				Attribute att = it.next();
				System.out.println(att.getName()+"="+att.getValue());
			}
			//迭代出他的子節點
			for(Iterator<Element> it = root.elementIterator();it.hasNext();)
			{
				Element e = it.next();
				System.out.println(e.getName());
			}
			//迭代出傳入參數的元素的節點!
			for(Iterator<Element> it = root.elementIterator("file");it.hasNext();)
			{
				Element e = it.next();
				System.out.println(e.getName());
			}

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

如果你曾不得不創建一個xml的文檔樹,爲了效率,我們提醒你去運用快速循環的方法以適應創建迭代對象的消耗爲每次循環。例如:

	public void tree(Element root)
	{
		for(int i = 0,size = root.nodeCount(); i < size ;i++)
			{
				Node node = root.node(i);
				if(node instanceof Element)
				{
					tree((Element) node);
				}
				else
				{
					System.out.println("node:"+node.getText());
				}
			}
	}
CREATE A NEW XML DOCUMENT(創建一個新的xml文檔對象)

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

經常你需要去創建一個新的文檔對象,這就是一個例子:

要用到了DocumentHelper方法。

Document myd = DocumentHelper.createDocument();


在節點或創建的節點上添加節點!

	Element root = document.addElement( "root" );

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

WRITE DOCUMENT TO FILE(把文件寫入文本中)

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

一個快速的容易的方法去寫入一個文檔用write()方法:

XMLWriter writer = new XMLWriter(new FileWriter("src/book.xml"));
			writer.write(root);
			writer.close();

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.

如果你想去改變輸出的格式,你可以選擇是一個漂亮的輸出還是一個壓實 的輸出!當然你也可以寫到一個OUTPUTSTREAM中,你都可以用write()

//創建一個漂亮的格式
			OutputFormat pre = OutputFormat.createPrettyPrint();
			//創建一個壓實的格式
			OutputFormat com = OutputFormat.createCompactFormat();
			XMLWriter writer = new XMLWriter(new FileWriter("src/book.xml"),pre);
			writer.write(root);
			writer.close();


CONVERT TO AND FROM STRING(由文檔到字符串的轉換)

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.

你可以把一個文檔對象或者是節點,元素,屬性等。變爲String用asXML()方法!

        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變爲文檔或者其他!

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

下一篇我們將討論xml的亂碼問題。



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章