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>

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值