1. 读取

1.1 数据库数据示例

<?xml version="1.0" encoding="GB2312"?>
<report name="su" pagetype="A4" width="210" height="297" orientation="1" top="21" bottom="21" left="25" right="25">
  <title title_content="" fontface="仿宋体" fontsize="14" fontbold="#fb[1]" fontitalic="#fi[1]" underline="" dline="" color="#000000" />
  <head left="&[制作人]&[YYYY年YY月]" center="&[制作人]" right="&[日期]" fontface="仿宋体" fontsize="10" fontbold="#fb[1]" fontitalic="#fi[1]" underline="#fu[1]" dline="" color="#000000" lHeadHomeShow="" mHeadHomeShow="" rHeadHomeShow="" />
  <tail left="&[时间]" center="&[总人数]" right="&[制作人]" fontface="仿宋体" fontsize="10" fontbold="#fb[1]" underline="" fontitalic="" dline="" color="#000000" lFootHomeShow="" mFootHomeShow="mFootChecked" rFootHomeShow="" />
  <body fontface="仿宋体" fontsize="10" fontbold="#fb[1]" fontitalic="" underline="" color="#000000" thead_fn="仿宋体" thead_fz="10" thead_fb="" thead_fu="" thead_fi="" thead_fc="#000000" />
</report>

1.2 读取和转换

String sql = "select xml_style from LName where Tabid=?";
ArrayList<String> values = new ArrayList<String>();
values.add(tabid);
rs = dao.search(sql,values);
while(rs.next())
{
    xml = Sql_switcher.readMemo(rs,"xml_style");
}
if(xml==null||xml.equals(""))
{
    xml = "<?xml version=\"1.0\" encoding=\"GB2312\"?>  <report> </report>  ";
}
byte bt[]=xml.getBytes();
ByteArrayInputStream input=new ByteArrayInputStream(bt);
SAXBuilder saxbuilder = new SAXBuilder();
doc = saxbuilder.build(input);

先将数据转换为byte格式,再转为字节数组输入流对象input。

  • 读取根节点

    Element element =doc.getRootElement();
  • 获取子节点

    element.getChild("title");
  • 获取节点内元素

    title.getAttributeValue("title_content");

2. 存储

2.1 转换为DOM类型

String xml = "<?xml version=\"1.0\" encoding=\"GB2312\"?> <report></report>";
byte bt[]=xml.getBytes();
ByteArrayInputStream input=new ByteArrayInputStream(bt);
SAXBuilder saxbuilder = new SAXBuilder();
Document doc = saxbuilder.build(input);
Element report = doc.getRootElement();
report.setAttribute("name",userView==null?"":userView.getUserName());

2.2 添加子节点

Element title = new Element("title");
report.addContent(title);

2.3DOM转为String

XMLOutputter outputter = new XMLOutputter();
Format format=Format.getPrettyFormat();
format.setEncoding("GB2312");
outputter.setFormat(format);
String newXML=outputter.outputString(doc);