在做BlackBerry的项目中,J2ME环境下通过DOM读取xml还是很简单的,但在修改了DOM后对与xml的保存成了问题,研究了一天也没有找到现成的可用代码,故自己写了一个类,遍历DOM然后输出String,由于我的xml只涉及到节点属性,故只做了属性这块,节点内容和命名空间等,大家自己可以加入即可,大家如有什么更好的办法,一定要告诉我啊,呵呵,具体类如下:
import org.w3c.dom.*;
public class BodyUtil {
String bodystr = "<?xml version='1.0' encoding='gb2312'?>";
public BodyUtil() {
}
public String DomToString(Document doc)
{
try
{
Element root = doc.getDocumentElement();
root.normalize();
bodystr = bodystr+"<"+root.getNodeName()+">";
NodeList tmp_nl = root.getChildNodes();
getNode(tmp_nl);
bodystr = bodystr+"</"+root.getNodeName()+">";
}
catch(Exception e)
{e.printStackTrace();}
return bodystr;
}
public void getNode(NodeList tmp_nl)
{
for(int i=0;i<tmp_nl.getLength();i++)
{
Node tmp_node = tmp_nl.item(i);
bodystr = bodystr +"<"+tmp_node.getNodeName();
if(tmp_node.getAttributes().getLength()>0)
{
for(int n=0;n<tmp_node.getAttributes().getLength();n++)
{
Node att_node =tmp_node.getAttributes().item(n);
bodystr = bodystr + " "+att_node.getNodeName()+"='"+att_node.getNodeValue()+"' ";
}
}
bodystr = bodystr + ">";
NodeList tmp = tmp_nl.item(i).getChildNodes();
getNode(tmp);
bodystr = bodystr +"</"+tmp_nl.item(i).getNodeName()+">";
}
}
}
调用如下:
BodyUtil bu = new BodyUtil();
String tmpstr = bu.DomToString(document);