星期五, 十一月 30, 2007

dom4j两种创建namespace的方法的差异!

由于要生成符合CNML国家标准的文件,涉及到一系列的问题。尤其是用dom4j传教namespace时,不同的方法,效果很有不同,记录在此。

dom4j 两种创建XML Document方法中命名空间的差异!

Namespace namespace ...

//第一种方法
Document doc = DocumentHelper.createDocument();
Element root = doc.addElement("Root", namespace.getURI());
Element eResultMessage = root.addElement("ResultMessage");

结果为:
<Root xmlns="http://aaaaaa">
<resultmessage>...</resultmessage>
</root>

//第二种方法
Document doc = DocumentHelper.createDocument();
Element root = doc.addElement("Root");
root.add(namespace);
Element eResultMessage = root.addElement("ResultMessage");

结果为:
<Root xmlns="http://aaaaaa">
<resultmessage xmlns="">...</resultmessage>
</root><
只要是设置了父元素的Namespace,子元素就会自动出现xmlns=""的
====================
Namespace ns = new Namespace("","http://www.cnml.org.cn/2005/CNMLSchema");
Document myDocument = DocumentHelper.createDocument();
Element root = myDocument.addElement("CNML", ns.getURI());
=============
Namespace ns = new Namespace("","http://www.cnml.org.cn/2005/CNMLSchema");
Document myDocument = DocumentHelper.createDocument();
Element root = myDocument.addElement("CNML");
root.add(ns);
====================