JDOM 中的命名空间(默认) [英] Namespaces (Default) in JDOM
问题描述
我正在尝试使用最新的 JDOM 包生成 XML 文档.我在处理根元素和命名空间时遇到了问题.我需要生成这个根元素:
I am trying to produce a XML document using the newest JDOM package. I'm having trouble with the root element and the namespaces. I need to produce this root element:
<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 之后的下一个元素也具有默认命名空间,这破坏了验证:
However, the next element after ManageBuildingsRequest has the default namespace as well, which breaks the validation:
<customer xmlns="">
有什么帮助吗?感谢您抽出宝贵时间.
Any help? Thank you for your time.
推荐答案
构造函数 创建它时没有命名空间.您应该使用带有 Namespace
作为参数的构造函数.您还可以为根元素和客户元素重用相同的 Namespace
对象.
The constructor you're using for the customer
element creates it with no namespace. You should use the constructor with the Namespace
as parameter. You can also reuse the same Namespace
object for both root and customer elements.
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
这篇关于JDOM 中的命名空间(默认)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!