Namespaces (Default) in JDOM

你离开我真会死。 提交于 2019-12-03 14:50:56

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

Here's an alternate approach that implements a custom XMLOutputProcessor that skips emitting empty namespace declarations:

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);
        }
    }
}
GiovanyMoreno

I tried javanna's code but unfortunately it kept on generating the empty namespaces in the document's contents. After trying bearontheroof's code the XML exported just fine.

You would have to do something like this after creating the custom class:

CustomXMLOutputProcessor output = new CustomXMLOutputProcessor();
output.process(new FileWriter("/path/to/folder/generatedXML.xml"), Format.getPrettyFormat(), document);
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!