网站地图    收藏   

主页 > 前端 > css教程 >

JDom解析xml - html/css语言栏目:html.css - 自学php

来源:自学PHP网    时间:2015-04-14 14:51 作者: 阅读:

[导读] import java io FileWriter;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 XMLOu...

import java.io.FileWriter;
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 JDomTest1
{
	public static void main(String[] args) throws Exception
	{
		Document document = new Document();

		Element root = new Element("root");

		document.addContent(root);

		Comment comment = new Comment("This is my comments");

		root.addContent(comment);

		Element e = new Element("hello");

		e.setAttribute("sohu", "www.sohu.com");

		root.addContent(e);

		Element e2 = new Element("world");

		Attribute attr = new Attribute("test", "hehe");

		e2.setAttribute(attr);

		e.addContent(e2);

		e2.addContent(new Element("aaa").setAttribute("a", "b")
				.setAttribute("x", "y").setAttribute("gg", "hh").setText("text content"));

		
		Format format = Format.getPrettyFormat();
		
		format.setIndent("    ");
//		format.setEncoding("gbk");
		
		XMLOutputter out = new XMLOutputter(format);

		out.output(document, new FileWriter("jdom.xml"));
			

	}
}


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

import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

public class JDomTest2
{
	public static void main(String[] args) throws Exception
	{
		SAXBuilder builder = new SAXBuilder();
		
		Document doc = builder.build(new File("jdom.xml"));
		
		Element element = doc.getRootElement();
		
		System.out.println(element.getName());
		
		Element hello = element.getChild("hello");
		
		System.out.println(hello.getText());
		
		List list = hello.getAttributes();
		
		for(int i = 0 ;i < list.size(); i++)
		{
			Attribute attr = (Attribute)list.get(i);
			
			String attrName = attr.getName();
			String attrValue = attr.getValue();
			
			System.out.println(attrName + "=" + attrValue);
		}
		
		hello.removeChild("world");
		
		XMLOutputter out = new XMLOutputter(Format.getPrettyFormat().setIndent("    "));
		
		
		out.output(doc, new FileOutputStream("jdom2.xml"));		
		
	}
}


自学PHP网专注网站建设学习,PHP程序学习,平面设计学习,以及操作系统学习

京ICP备14009008号-1@版权所有www.zixuephp.com

网站声明:本站所有视频,教程都由网友上传,站长收集和分享给大家学习使用,如由牵扯版权问题请联系站长邮箱904561283@qq.com

添加评论