JDOM中的命名空间(默认)

jn1*_*1kk 6 java xml 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">
Run Code Online (Sandbox Code Playgroud)

我用这个代码:

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
Run Code Online (Sandbox Code Playgroud)

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

<customer xmlns="">
Run Code Online (Sandbox Code Playgroud)

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

jav*_*nna 16

您为该元素使用的构造函数customer创建它没有名称空间.您应该将构造函数与Namespaceas参数一起使用.您还可以为Namespace根元素和客户元素重用相同的对象.

Namespace namespace = Namespace.getNamespace("http://www.energystar.gov/manageBldgs/req");
Element root = new Element("ManageBuildingsRequest", namespace);
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", namespace);
root.addContent(customer);
doc.addContent(root); // doc jdom Document
Run Code Online (Sandbox Code Playgroud)

  • 你是对的,但我不太清楚为什么.我必须将命名空间传递给我经常使用的每个孩子 - 变得非常痛苦,但这解决了它.谢谢. (2认同)