JDom解析xml(一)


(一)利用JDOM生成xml文件

 

package com.huawei;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.jdom.Attribute;
import org.jdom.Comment;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;



public class Demo1 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		test1();
	}

	public static void test1(){
		Document document=new Document();
		Element rootElement=new Element("root");
		document.addContent(rootElement);
		
		Comment comment=new Comment("this is comment");
		rootElement.addContent(comment);
		
		Element e=new Element("hello");
		e.setAttribute("baidu","www.baidu.com");
		rootElement.addContent(e);
		
		Element e2=new Element("World");
		Attribute attribute=new Attribute("wangyi", "www.163.com");
		e2.setAttribute(attribute);
		rootElement.addContent(e2);
		
		Element e3=new Element("wuhan");
		e3.setAttribute("huawei", "www.huawei.com").setAttribute("souhu", "www.souhu.com");//方法链的编程风格
		rootElement.addContent(e3);
		
		//Format format=Format.getRawFormat();//默认的格式
		Format format=Format.getPrettyFormat();
		format.setIndent("    ");
		XMLOutputter out=new XMLOutputter(format);
		try {
			out.output(document, new FileOutputStream("jdom2.xml"));
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} 
	}

}

(二)解析普通的xml文件

下面是xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <!--This is comment-->
    <百度 名字="www.baidu.com">
        <!--This is comment too-->
    </百度>
    <搜狐 名字="www.souhu.com" />
</root>



 解析上面的zz.xml文件的代码如下:

 

	public static void test1(){
		SAXBuilder saxBuilder=new SAXBuilder();
		try {
			Document document=saxBuilder.build("zz.xml");
			Element root=document.getRootElement();
			System.out.println(root.getName());
			Element baiduElement=root.getChild("百度");
			/*System.out.println(baiduElement.getName()+"...."+baiduElement.getValue());*/
			List<Attribute> list=baiduElement.getAttributes();
			int size=list.size();
			for(int i=0;i<size;i++){
				Attribute attribute=list.get(i);
				String name=attribute.getName();
				String value=attribute.getValue();
				System.out.println(name+"..."+value);
				}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

 

输出如下:

root
名字...www.baidu.com

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值