dom4j根据xml节点name值来遍历节点数据

package com.loymtech.test;

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

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

/**
 * 根据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对象


     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());
  }
 }

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

猜你喜欢

转载自skyfar666.iteye.com/blog/1895405