dom4j根據xml節點name值來遍歷節點數據

package com.loymtech.test;java

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

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

/**
 * 根據xml節點name來遍歷節點數據
 *
 * @author lenovo
 *
 */
public class TestDom4J {
 public void modifyDocument(File inputXml) {
  try {
   SAXReader saxReader = new SAXReader();
   Document document = saxReader.read(inputXml);
   Element rootElt = document.getRootElement();
   Iterator iter = rootElt.elementIterator("occasion");
   while (iter.hasNext()) {
    Element recordEle = (Element) iter.next();
    String name = recordEle.attributeValue("name");
    if ("booking".equals(name)) {
     Iterator<Element> children = recordEle.elementIterator(); //元素的子元素的iterator,其中每一個元素都是Element對象xml


     while (children.hasNext()) {
      Element child = children.next();
      Iterator<Attribute> attributes = child
        .attributeIterator();
      while (attributes.hasNext()) {
       Attribute attribute = attributes.next();
       System.out.println(attribute.getName() + " : "
         + attribute.getValue());
      }
      System.out.println();
     }
    }
   }
  }對象

  catch (DocumentException e) {
   System.out.println(e.getMessage());
  }
 }blog

 public static void main(String[] argv) {
  TestDom4J dom4jParser = new TestDom4J();
  dom4jParser.modifyDocument(new File(
    "d:\\testfile\\123.xml"));
 }
}element

相關文章
相關標籤/搜索