`
orange5458
  • 浏览: 348303 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

XML JAVA解析 -- JDOM

    博客分类:
  • XML
阅读更多

OOP 解析 XML 的JAVA实现。

 

1.实例

 

package com.siyuan.xml;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import org.jdom.Attribute;
import org.jdom.Content;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.Text;
import org.jdom.input.DOMBuilder;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;

public class JDOMTest {
 
 public static void printElement(Element e) {
  System.out.println("Element : " + e.getName() + "---------------");
  List attributes = e.getAttributes();
  Iterator iterAttrs = attributes.iterator();
  while (iterAttrs.hasNext()) {
   Attribute attri = (Attribute) iterAttrs.next();
   System.out.println("Attribute " + attri.getName() + "=" + attri.getValue());
  }
  List contents = e.getContent();
  Iterator iter = contents.iterator();
  while (iter.hasNext()) {
   Content content = (Content) iter.next();
   if (content instanceof Element) {
    printElement((Element) content);
   } else if (content instanceof Text) {
    System.out.println(((Text) content).getText());
   }
  }
 }
 
 /**
  * @param args
  * @throws IOException
  * @throws JDOMException
  */
 public static void main(String[] args) throws JDOMException, IOException {
  // TODO Auto-generated method stub
  SAXBuilder builder = new SAXBuilder();
  builder.setValidation(true);
  Document document = builder.build("src/com/siyuan/xml/workers.xml");
  printElement(document.getRootElement());
  
  XMLOutputter transformer = new XMLOutputter();
  transformer.output(document, new FileOutputStream(new File("src/com/siyuan/xml/workers2.xml")));
 }

}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics