最近使用dom4j生成xml文件發現了一個問題,在給元素添加 xmlns屬性時,不會在文件中輸出來,後來到網上查找,發現了原來在創建元素對象的時候傳參就可以解決問題了。
e.g 要顯示的效果:
<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/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
。。。。。。
</beans>
剛開始(錯誤的方法):
Element root = document.addElement("beans");
root.addAttribute("xmlns","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/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsd");
生成xml文件(發現xmlns不會顯示)
<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/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
。。。。。。
</beans>
正確的方法:
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/beanshttp://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/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
。。。。。。
</beans>