dom4j: 生成的XML文件根節點 xmlns="" 的問題


使用dom4j寫入XML文件時,寫入完畢后發現root element中沒有 xmlns,也即是沒有命名空間。

正確的寫法如下:

Document document = DocumentHelper.createDocument();
        Element kmlElement = document.addElement(KML_ELEMENT_KML, "http://www.opengis.net/kml/2.2");

一定要在添加根節點時,即為其指定命名空間。其中, KML_ELEMENT_KML 是root element的名稱。

注意:不要通過類似 element.addNamspace("",url) 這樣的方式或類似下面的寫法

Element kmlElement = DocumentHelper.createElement(KML_ELEMENT_KML);
        kmlElement.addAttribute(KML_ATTRIBUTE_XMLNS, "http://www.opengis.net/kml/2.2");
        Document document = DocumentHelper.createDocument(kmlElement);

來為根element指定缺省的命名空間,這樣的做法就會出現生成的xml 根節點命名空間是空的問題。

不過下面的寫法仍然是對的(貌似只有xmlns需要注意這一點):

Element root = document.addElement("beans","http://www.springframework.org/schema/beans");
root.addAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
root.addAttribute("xmlns:p", "http://www.springframework.org/schema/p");
root.addAttribute("xsi:schemaLocation", "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd");

生成xml文件(發現xmlns可以出現了)

<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM