JDOM解析XML实例

发表于:2010-1-28 10:03

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:未知    来源:51Testing软件测试网采编

#
java

  import java.io.FileOutputStream;

  import java.util.List;

  import org.jdom.Document;

  import org.jdom.Element;

  import org.jdom.input.SAXBuilder;

  import org.jdom.output.XMLOutputter;

  public class TestJDomSax {

  /*<?xml version="1.0" encoding="UTF-8"?>

  <books>

  <book email=zhang@1.net>

  <name>li</name>

  <price>63.4</price>

  </book>

  </books>*/

  public static void main(String[] args) {

  // TODO Auto-generated method stub

  String filePath="lib.xml";

  try {

  SAXBuilder sax=new SAXBuilder(); // 创建一个sa

  Document doc=sax.build(filePath);  //得到Document对应的XML

  Element el=doc.getRootElement(); //得到根节点,对应books

  List<Element> list=el.getChildren("book");  //得到book节点集

  for(Element book:list){

  //取属性,并修改

  String email=book.getAttributeValue("email");//获取属性内容

  System.out.println(email);

  book.setAttribute("email",yuanjob@163.com);

  //取节点,并修改

  String name=book.getChildTextTrim("name"); //获取节点内容

  System.out.println(name);

  Element ele=book.getChild("name");

  ele.setText("yuan");

  //取节点,并修改

  String price=book.getChildTextTrim("price"); //获取节点内容

  System.out.println(price);

  Element eleprice=book.getChild("price");

  eleprice.setText("999");

  }

  XMLOutputter out=new XMLOutputter();

  out.output(doc,new FileOutputStream(filePath));

  } catch (Exception e) {

  e.printStackTrace();

  }

  }

  }

《2023软件测试行业现状调查报告》独家发布~

精彩评论

  • 最初的梦想666
    2010-1-28 14:18:02

    招聘:
    知名外资公司,java 开发的职位,Manager / Lead /SSE/SE , 英语好,考虑新机会的可给我发简历(也欢迎推荐)

    邮箱:happyzs9@163.com  , MSN: happyzs9@163.com

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号