webdn
 
  首页     免费截图     VIP会员区     广告Banner     技术文档     网站模板  
网站截图,网站每日新 !
虚拟主机 域名注册

 

XML 的 RUD

【摘 要】在工作中使用 XML 已经很长时间了,不过长久以来都是进行的读操作,或者在生成 XML 时完全使用 StringBuffer 来构造。进行完整的读取、添加、删除、修改还是最近的事情。

在工作中使用 XML 已经很长时间了,不过长久以来都是进行的读操作,或者在生成 XML 时完全使用 StringBuffer 来构造。进行完整的读取、添加、删除、修改还是最近的事情。在这里我采用的是 DOM4J,其实呢这些内容都很简单,如果愿意,各位大可直接参考官方的 Cookbook(http://www.dom4j.org/cookbook.html)和 Quick Start(http://www.dom4j.org/guide.html)。
  
对于给定的 XML 文件,其结构如下:


<propertysets>

<propertset name="rea_faculty" description="team">
 <field>10290</field>
</propertset>
<propertset name="faculty_lea" description="another team">
 <field>10286</field>
</propertset>
<propertset name="office" description="teams">
 <field>10287</field>
</propertset>

</propertysets>

  为以上 XML 文件构造 Propertys 类:

public class Propertys {

private String name;
private String description;
private String field;

public String getDescription() {
 return description;
}

public void setDescription(String description) {
 this.description = description;
}

public String getField() {
 return field;
}

public void setField(String field) {
 this.field = field;
}

public String getName() {
 return name;
}

public void setName(String name) {
 this.name = name;
}
}

读取方法(返回包含 Propertys 的列表):
  

(Element) lv.next();
  property.setName(el.attributeValue("name"));
  property.setDescription(el.attributeValue("description"));
  property.setField(el.elementText("field"));
  list.add(property);
  }
 } catch (Exception e) {
  e.printStackTrace();
 }
 return list;
}

添加新节点(成功返回 1 否则 0):
    

XMLWriter(out,outformat);
  writer.write(document);
  writer.close();
  return 1;
 } catch (Exception e) {
  e.printStackTrace();
 }
 return 0;
}

更新节点(按照 name 属性查找):
  

(Element) lv.next();
  if (el.attributeValue("name").equals(pro)) {
   el.setAttributeValue("name",property.getName());
   el.setAttributeValue("description",property.getDescription());
   el.element("field").setText(property.getField());
  }
  }

  OutputFormat outformat = OutputFormat.createPrettyPrint();
  outformat.setEncoding("GBK");
  FileWriter out = new FileWriter(
   System.getProperty("user.dir")
   +"/web/WEB-INF/ XMLWriter(out,outformat);
  writer.write(document);
  writer.close();
  return 1;
 } catch (Exception e) {
  e.printStackTrace();
 }
 return 0;
}

删除节点:
  

(Element) lv.next();
  if (el.attributeValue("name").equals(pro)) {
   el.detach();
  }
  }

  OutputFormat outformat = OutputFormat.createPrettyPrint();
  outformat.setEncoding("GBK");
  FileWriter out = new FileWriter(
   System.getProperty("user.dir")
   +"/web/WEB-INF/ XMLWriter(out,outformat);
  writer.write(document);
  writer.close();
  return 1;
 } catch (Exception e) {
  e.printStackTrace();
 }
 return 0;
}


  | 
点击这里给我发消息 | 关于WebDN  |  站点地图  |  联系我们  |  WebDN 会员  |  支付方式  |  友情链接  |  隐私政策
© 2004-2008 WebDN.com 版权所有. 沪ICP备05040479号