`

jdom解析XML文件

阅读更多

需要jdom.jar

类文件: jdom.java

 

import java.io.File;

import java.io.IOException;

import java.util.Iterator;

import java.util.List;

import org.jdom.Attribute;

import org.jdom.Document;

import org.jdom.Element;

import org.jdom.JDOMException;

import org.jdom.ProcessingInstruction;

import org.jdom.input.SAXBuilder;

import com.sun.xml.internal.bind.v2.runtime.Name;

/**

 * jdom解析xml文件

 * 

 * @author ly * 

 */

public class jdom {

 

 public void parseXml(File xmlFile) {

  SAXBuilder sax = new SAXBuilder();//在内存中建立一个sax文档模型

  try {

   Document xmlDom = sax.build(xmlFile);//创建文档

   //获得文件的根元素

   Element root = xmlDom.getRootElement();

   System.out.println("根元素是:"+root.getName());

 

   //获得根元素的子节点

   List childList = root.getChildren();

   Iterator listIt = childList.iterator();

   while(listIt.hasNext()){

    Element element = (Element)listIt.next();

    System.out.println("孩子结点是:"+element.getName());

   }

 

   //获得第一个孩子结点

   Element firstChild = (Element) childList.get(0);

   Element twoChild=(Element) childList.get(1);

   System.out.println(twoChild);

   System.out.println(firstChild);

   //获得孩子结点的属性

   List attrList = firstChild.getAttributes();

   Iterator attrIt = attrList.iterator();

   while(attrIt.hasNext()){

    Attribute  attr = (Attribute ) attrIt.next();

    System.out.println("第一个元素的属性是:"+attr.getName());

    //获得属性的值

    System.out.println("属性的值是:"+attr.getValue());

    //获得属性的类型

    System.out.println("属性的类型是:"+attr.getAttributeType());

   }

 

   List sonList = firstChild.getChildren();

   Iterator sonIt = sonList.iterator();

   while(sonIt.hasNext()){

    Element temp = (Element)sonIt.next();

    System.out.println("属性"+temp.getName()+"的值是:"+temp.getValue());

   }

 

 

  } catch (JDOMException e) {

   e.printStackTrace();

  } catch (IOException e) {

   e.printStackTrace();

  }

 }

 

 public static void main(String[] args) {

  jdom test = new jdom();

  test.parseXml(new File("persons.xml"));

 }

}

 

xml 文件:person.xml直接放到工程文件下

 

<?xml version="1.0" encoding="ISO-8859-1" ?>

<configuration xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    xsi:noNamespaceSchemaLocation="config.xsd">

 

 <font chr="hphua">

  <name color="blue">hpjianhua</name>

  <size>30</size>

 </font>

 

</configuration>

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics