使用JDOM生成和解析XML
2014-11-13 16:16
411 查看
到官方网站下载JDOM包http://www.jdom.org/
注意的是,版本1和版本2的类路径已经变更,如果你是更新使用版本2,则需要重新编译你的代码
请您到ITEYE网站看原创,谢谢!
http://cuisuqiang.iteye.com/ !
自建博客地址:http://www.javacui.com/ ,内容与ITEYE同步!
注意的是,版本1和版本2的类路径已经变更,如果你是更新使用版本2,则需要重新编译你的代码
package com.test; import java.io.FileOutputStream; import java.util.List; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.input.SAXBuilder; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; /** * @说明 JDom生成解析XML * @author cuisuqiang * @version 1.0 * @since */ @SuppressWarnings("unchecked") public class JDomDemo { public static void main(String[] args) { String file = "C:\\p.xml"; // 文件存放位置 JDomDemo dj = new JDomDemo(); dj.createXml(file); dj.parserXml(file); } /** * 生成XML * @param filePath 文件路径 */ public void createXml(String fileName) { Element root = new Element("persons"); Document document = new Document(root); Element person = new Element("person"); root.addContent(person); Element name = new Element("name"); name.setText("java小强"); person.addContent(name); Element sex = new Element("sex"); sex.setText("man"); person.addContent(sex); Element age = new Element("age"); age.setText("23"); person.addContent(age); XMLOutputter XMLOut = new XMLOutputter(); try { Format f = Format.getPrettyFormat(); f.setEncoding("UTF-8");//default=UTF-8 XMLOut.setFormat(f); XMLOut.output(document, new FileOutputStream(fileName)); } catch (Exception e) { e.printStackTrace(); } } /** * 解析XML * @param filePath 文件路径 */ public void parserXml(String fileName) { try { SAXBuilder builder = new SAXBuilder(); Document document = builder.build(fileName); Element root = document.getRootElement(); List persons = root.getChildren("person"); for (int i = 0; i < persons.size(); i++) { Element person = (Element) persons.get(i); List pros = person.getChildren(); for (int j = 0; j < pros.size(); j++) { Element element = (Element) pros.get(j); System.out.println(element.getName() + ":" + element.getValue()); } } } catch (Exception e) { e.printStackTrace(); } } }
请您到ITEYE网站看原创,谢谢!
http://cuisuqiang.iteye.com/ !
自建博客地址:http://www.javacui.com/ ,内容与ITEYE同步!
相关文章推荐
- 使用dom4j和jdom解析与生成字符串型XML的代码示例
- xml解析3:使用jdom框架进行对xml文档生成和读写解析
- 使用JDOM生成和解析XML
- 使用dom4j和jdom解析与生成字符串型XML的代码示例
- 使用Jdom解析XML
- using libxml2连载(2 使用简介与xml tree的生成解析)
- 使用JDOM解析XML文档
- 使用JDOM解析XML
- JDOM入门:使用JDOM解析XML(转)
- 使用JDOM生成XML文档
- JDOM入门:使用JDOM解析XML
- 使用JDOM解析XML
- 使用JDOM解析XML
- 使用JDOM解析XML
- 使用dom4j来解析,生成xml文件
- JDOM入门:使用JDOM解析XML
- 使用jdom操作xml数据,生成含Jtree的applet(转载 Jagie 原创 )
- 使用jdom解析xml
- 使用jdom操作xml数据,生成含Jtree的applet(转载 Jagie 原创 )
- 使用jdom操作xml数据,生成含Jtree的applet