Java中使用dom4j解析XML字符串以及Oracle中Clob数据类型转换成String类型范例:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.sql.SQLException;
import java.util.Iterator;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class XMLPaser
{
public static String paser(String originalXMLStr)
{
SAXReader saxReader = new SAXReader();
Document document = null;
try
{
document = saxReader.read(new StringReader(originalXMLStr));
} catch (DocumentException e)
{
e.printStackTrace();
return null;
}
Element root = document.getRootElement();
for (Iterator i = root.elementIterator(); i.hasNext();)
{
Element ele = (Element) i.next();
if (ele.getName().equals("ccd")) // XML node
{
// <ccd a="" b="" c="" d="" />
Attribute attr_a = ele.attribute("a");// XML node 'ccd' attribute a
Attribute attr_b = ele.attribute("b");// XML node 'ccd' attribute b
Attribute attr_c = ele.attribute("c");// XML node 'ccd' attribute c
Attribute attr_d = ele.attribute("d");// XML node 'ccd' attribute d
if (attr_a != null)
{
attr_a.setText("");// change attribute a's value;
}
}
}
String updXml = document.asXML();
updXml = updXml.replaceAll("/n", "");
updXml = updXml.replaceAll("/t", "");
return updXml;
}
public static String ClobToStr(oracle.sql.CLOB clob) throws SQLException,
IOException
{
Reader reader = clob.getCharacterStream();
BufferedReader br = new BufferedReader(reader);
String str = br.readLine();
StringBuffer sb = new StringBuffer();
while (str != null)
{
sb.append(str);
str = br.readLine();
}
return sb.toString();
}
}