使用dom4j和jdom解析与生成字符串型XML的代码示例

记录一下使用dom4j和jdom这两个API处理字符串型XML的方法,虽然网上也有很多这样的文章,但我还是想再写一遍,方便自己查找。
dom4j是1.6.1版本,jdom是1.1版,代码没什么技术含量,就是API的使用而已,所以没加注释。

import java.io.IOException;
import java.io.StringWriter;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

public class Dom4JHandle {

private static final String xmlString = "<books><book price=\"108\"><name>Java编程思想</name><author>Bruce Eckel</author></book><book price=\"52\"><name>Effective Java</name><author>Joshua Bloch</author></book><book price=\"118\"><name>Java 7入门经典</name><author>Ivor Horton</author></book></books>";

public static void main(String[] args) {
parseXml(xmlString);
assembleXml();
}

public static void parseXml(String xmlString) {
try {
Document doc = DocumentHelper.parseText(xmlString);
Element root = doc.getRootElement();
@SuppressWarnings("unchecked")
List<Element> elements = root.elements();
for(Element element : elements) {
System.out.println("name=" + element.elementText("name") + "\tauthor=" + element.elementText("author")
+ "\tprice=" + element.attributeValue("price"));
}
} catch (DocumentException e) {
e.printStackTrace();
}
}

public static String assembleXml() {
Document doc = DocumentHelper.createDocument();
Element root = doc.addElement("books");
Element book = root.addElement("book");
book.addAttribute("price", "108");
book.addElement("name").setText("Java编程思想");
book.addElement("author").setText("Bruce Eckel");
book = root.addElement("book");
book.addAttribute("price", "52");
book.addElement("name").setText("Effective Java");
book.addElement("author").setText("Joshua Bloch");
book = root.addElement("book");
book.addAttribute("price", "118");
book.addElement("name").setText("Java 7入门经典");
book.addElement("author").setText("Ivor Horton");
OutputFormat format = OutputFormat.createCompactFormat(); //createPrettyPrint() 层次格式化
StringWriter writer = new StringWriter();
XMLWriter output = new XMLWriter(writer, format);
try {
output.write(doc);
writer.close();
output.close();
System.out.println(writer.toString());
} catch (IOException e) {
e.printStackTrace();
return null;
}
return writer.toString();
}
}


dom4j还可以配合xpath一起使用,一般来说用不上,不过xml比较复杂,而需求又比较特殊的时候就需要它来配合了,不过不用完全记住那些规则,可以去w3cschool网站在线查询:
http://www.w3school.com.cn/xpath/index.asp

import java.io.StringReader;
import java.util.List;

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 JdomHandle {

private static final String xmlString = "<books><book price=\"108\"><name>Java编程思想</name><author>Bruce Eckel</author></book><book price=\"52\"><name>Effective Java</name><author>Joshua Bloch</author></book><book price=\"118\"><name>Java 7入门经典</name><author>Ivor Horton</author></book></books>";

public static void main(String[] args) {
parseXml(xmlString);
assembleXml();
}

public static void parseXml(String xmlString) {
SAXBuilder builder = new SAXBuilder();
Document doc = null;
try {
doc = builder.build(new StringReader(xmlString));
Element root = doc.getRootElement(); // 根元素
@SuppressWarnings("unchecked")
List<Element> list = root.getChildren();
if (list != null) {
for (Element element : list) {
System.out.println("name=" + element.getChildText("name") + "\tauthor="
+ element.getChildText("author") + "\tprice=" + element.getAttributeValue("price"));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}

public static String assembleXml() {
Document doc = new Document();
Element root = new Element("books");
Element book = new Element("book");
Element name = new Element("name");
Element author = new Element("author");
book.setAttribute("price", "108");
name.addContent("Java编程思想");
author.addContent("Bruce Eckel");
book.addContent(name);
book.addContent(author);
root.addContent(book);
book = new Element("book");
name = new Element("name");
author = new Element("author");
book.setAttribute("price", "52");
name.addContent("Effective Java");
author.addContent("Joshua Bloch");
book.addContent(name);
book.addContent(author);
root.addContent(book);
book = new Element("book");
name = new Element("name");
author = new Element("author");
name.addContent("Java 7入门经典");
author.addContent("Ivor Horton");
book.setAttribute("price", "118");
book.addContent(name);
book.addContent(author);
root.addContent(book);
doc.addContent(root);
XMLOutputter xo = new XMLOutputter(Format.getCompactFormat()); // getPrettyFormat() 层次格式化
System.out.println(xo.outputString(doc));
return xo.outputString(doc);
}
}
该项目采用dom4j从数据库表中生成xml数据 项目文档、数据库建表语句均已放置在项目中。 关键代码如下: public String getXml(Connection conn, int rm_id, String path) { //声明xml字符串 String fileString = ""; //创建DAO对象 MachineroomDao machineroom_dao = new MachineroomDao(); Cab_equipmentDao cab_equipment_dao = new Cab_equipmentDao(); Equip_configDao equip_config_dao = new Equip_configDao(); EquipmentDao equipment_dao = new EquipmentDao(); //添加room,第一层 Machineroom machineroom_dto = machineroom_dao.findById(conn, rm_id);//设置房间号 //获取个属性的值.如果为null,将属性设为"" String getMr_id = new Integer(machineroom_dto.getMr_id()).toString(); String getMr_name = machineroom_dto.getMr_name(); if(getMr_id == null) getMr_id = ""; if(getMr_name == null) getMr_name = ""; Document document = DocumentHelper.createDocument(); Element rooms_racks = document.addElement("rooms-racks"); Element room = rooms_racks.addElement("room"); room.addAttribute("id", getMr_id); room.addAttribute("name", getMr_name); room.addAttribute("isSelected", "true"); //添加rack,第二层 List<Cab_equipment> cab_equipment_list = cab_equipment_dao.findById(conn, path, machineroom_dto.getMr_id()); for (int i = 0; i < cab_equipment_list.size(); i++) { Cab_equipment cab_equipment_dto = cab_equipment_list.get(i); //获取个属性的值.如果为null,将属性设为"" String getE_id = cab_equipment_dto.getE_id(); String getEqucab_name = cab_equipment_dto.getEqucab_name(); String getX = cab_equipment_dto.getX() + ""; String getY = cab_equipment_dto.getY() + ""; String getZ = cab_equipment_dto.getZ() + ""; String getLongs = cab_equipment_dto.getLongs() + ""; String getWidth = cab_equipment_dto.getWidth() + ""; String getHighs = cab_equipment_dto.getHighs() + ""; String getRotate_angle = cab_equipment_dto.getRotate_angle(); if(getE_id == null) getE_id = ""; if(getEqucab_name == null) getEqucab_name = ""; if(getRotate_angle == null) getRotate_angle = ""; //将float后的".0"去掉 if(cab_equipment_dto.getX()%1 == 0) getX = (int)cab_equipment_dto.getX()+""; if(cab_equipment_dto.getY()%1 == 0) getY = (int)cab_equipment_dto.getY()+""; if(cab_equipment_dto.getZ()%1 == 0) getZ = (int)cab_equipment_dto.getZ()+""; if(cab_equipment_dto.getHighs()%1 == 0) getHighs = (int)cab_equipment_dto.getHighs()+""; Element rack = room.addElement("rack"); rack.addAttribute("id", getE_id); rack.addAttribute("name", getEqucab_name); rack.addAttribute("x", getX); rack.addAttribute("y", getY); rack.addAttribute("z", getZ); rack.addAttribute("lengthX", getLongs); rack.addAttribute("lengthY", getWidth); rack.addAttribute("lengthZ", getHighs); rack.addAttribute("rotation", getRotate_angle); //添加device,第三层 int u = 0;//表示需要计算的u高,其xml的属性为uplace int count = 0;//计数器,临时变量 int count2 = 0; List<Equip_config> equip_config_list = equip_config_dao.findByLocation(conn, cab_equipment_dto.getE_id()); for (int j = 0; j < equip_config_list.size(); j++) { Equip_config equip_config_dto = equip_config_list.get(j); Equipment equipment_dto = equipment_dao.findBySerial(conn, equip_config_dto.getSerial()); //获取个属性的值.如果为null,将属性设为"" String getSerial = equip_config_dto.getSerial(); String getEquipmentname = equip_config_dto.getEquipmentname(); String getEq_typecn = equipment_dto.getEq_typecn(); String getImagepath = equip_config_dto.getImagepath(); String getStorey = equip_config_dto.getStorey(); //String getU = equip_config_dto.getU() + ""; if(getSerial == null) getSerial = ""; if(getEquipmentname == null) getEquipmentname = ""; if(getEq_typecn == null) getEq_typecn = ""; if(getImagepath == null) getImagepath = ""; if(getStorey == null) getStorey = ""; int getU = equip_config_dto.getU(); //处理u高 if(getU != 0){ count++; } if(count2==0){ if(count == 1){ u = 2; } }else{ Equip_config equip_config_dto_temp = equip_config_list.get(count2 - 1); Equipment equipment_dto_temp = equipment_dao.findBySerial(conn, equip_config_dto_temp.getSerial()); int getU_temp = equip_config_dto_temp.getU(); if(count == 1){ u = 2; }else { if(getU_temp == 0){ u = u + getU_temp/10 + 0; } else { if(getU_temp == 0){ u = u + getU_temp/10 +2; }else { u = u + getU_temp/10 + 1 + 2; } } } } count2++; String uplace = u + ""; String GetU = getU + ""; if(getU == 0) { uplace = "0"; }//u高处理完毕 Element device = rack.addElement("device"); device.addAttribute("num", getSerial); device.addAttribute("name", getEquipmentname); device.addAttribute("type", getEq_typecn); device.addAttribute("image", getImagepath); //device.addAttribute("storey", getStorey);//设备所在的层数,该属性不在xml中展示 device.addAttribute("uplace", uplace);//计算得来的u高 device.addAttribute("uheight", GetU);//图片的高度 } } //设置xml输出格式 OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding("UTF-8"); StringWriter out = new StringWriter(); XMLWriter xmlWriter = new XMLWriter(out, format); try { xmlWriter.write(document); fileString = out.toString(); xmlWriter.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return fileString; }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值