JDOM中的命名空间(默认)

我正在尝试使用最新的JDOM包生成XML文档。 我在使用根元素和命名空间时遇到了麻烦。 我需要生成这个根元素:

 

我用这个代码:

 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之后的下一个元素也具有默认命名空间,这会破坏validation:

  

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

您用于customer元素的构造函数创建它没有名称空间。 您应该使用带有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", "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 

这是一种实现自定义XMLOutputProcessor的替代方法,该方法跳过发出空命名空间声明:

 public class CustomXMLOutputProcessor extends AbstractXMLOutputProcessor { protected void printNamespace(Writer out, FormatStack fstack, Namespace ns) throws java.io.IOException { System.out.println("namespace is " + ns); if (ns == Namespace.NO_NAMESPACE) { System.out.println("refusing to print empty namespace"); return; } else { super.printNamespace(out, fstack, ns); } } } 

我尝试了javanna的代码,但不幸的是它继续在文档的内容中生成空名称空间。 在尝试了bearontheroof的代码之后,XML导出就好了。

在创建自定义类之后,您必须执行以下操作:

 CustomXMLOutputProcessor output = new CustomXMLOutputProcessor(); output.process(new FileWriter("/path/to/folder/generatedXML.xml"), Format.getPrettyFormat(), document);