java – JDOM中的命名空间(默认)

我正在尝试使用最新的JDOM包生成 XML文档.我遇到了根元素和命名空间的问题.我需要生成这个根元素:
<ManageBuildingsRequest 
    xmlns="http://www.energystar.gov/manageBldgs/req" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://www.energystar.gov/manageBldgs/req 
                        http://estar8.energystar.gov/ESES/ABS20/Schemas/ManageBuildingsRequest.xsd">

我用这个代码

Element root = new Element("ManageBuildingsRequest");
root.setNamespace(Namespace.getNamespace("http://www.energystar.gov/manageBldgs/req"));
Namespace XSI = Namespace.getNamespace("xsi","http://www.w3.org/2001/XMLSchema-instance");
root.addNamespaceDeclaration(XSI);
root.setAttribute("schemaLocation","http://www.energystar.gov/manageBldgs/req http://estar8.energystar.gov/ESES/ABS20/Schemas/ManageBuildingsRequest.xsd",XSI);

Element customer = new Element("customer");
root.addContent(customer);
doc.addContent(root); // doc jdom Document

但是,ManageBuildingsRequest之后的下一个元素也具有认命名空间,这会破坏验证:

<customer xmlns="">

有帮助吗?感谢您的时间.

解决方法

您用于customer元素的 constructor创建它时没有命名空间.您应该使用带有Namespace的构造函数作为参数.您还可以为root和customer元素重用相同的Namespace对象.
Namespace namespace = Namespace.getNamespace("http://www.energystar.gov/manageBldgs/req");
Element root = new Element("ManageBuildingsRequest",namespace);
Namespace XSI = Namespace.getNamespace("xsi",XSI);

Element customer = new Element("customer",namespace);
root.addContent(customer);
doc.addContent(root); // doc jdom Document

相关文章

应用场景 C端用户提交工单、工单创建完成之后、会发布一条工...
线程类,设置有一个公共资源 package cn.org.chris.concurre...
Java中的数字(带有0前缀和字符串)
在Java 9中使用JLink的目的是什么?
Java Stream API Filter(过滤器)
在Java中找到正数和负数数组元素的数量