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);
- 为什么java中的processBuilder会在5分钟后挂起?
- 土耳其人的小写字母点缀我
- 有谁知道我在哪里可以找到“Orto”Javascript JVM?
- 在解析包含xi的xml时遇到问题:包含jaxb
- 无法加载bean:type:org.apache.struts2.views.gxp.inject.InjectedObjectContainer
- AspectJ + Junit + Maven – 在测试中识别切入点但NoSuchMethodError:aspectOf()exception抛出
- Java Scanner类中的字符串格式
- 当请求来自Web服务器而不是Web浏览器时,HTTPSession的创建如何工作?
- XSD有2个根元素(一次1个)