mardi 24 février 2015

Unwanted Dom4J Namespace



When creating a document with a default namespace <root xmlns="....">using DOM4J, I get the following output on writing to file.



<?xml version="1.0" encoding="UTF-8"?>

<root xmlns="http:/foo.bar">
<foo xmlns="">bar</foo> <!-- unwanted xmlns="" on foo -->
</root>


What I expected (and want) is for foo to be <foo> not <foo xmlns="">. Here is some demo code



import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Namespace;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

public class App {

public static void main(String[] args) throws Exception {
Namespace xmlns = DocumentHelper.createNamespace("", "http:/foo.bar");
Element root = DocumentHelper.createElement("root");
root.add(xmlns);

Document document = DocumentHelper.createDocument();
document.setRootElement(root);

Element child = DocumentHelper.createElement("foo");
child.setText("bar");
root.add(child);

OutputFormat format = OutputFormat.createPrettyPrint();
XMLWriter writer = new XMLWriter( System.out, format );
writer.write( document );
}
}


How do I remove the extra attribute from <foo>? I'm happy to use a different library if that would be easier.


SOLUTION


The answer below together with this question helped solve my issue. I have also included the corrected code below:



import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Namespace;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

public class App {

public static void main(String[] args) throws Exception {
Document document = DocumentHelper.createDocument();
Element root = document.addElement("root");

Namespace xmlns = Namespace.get("http:/foo.bar");
root.add(xmlns);

root.addElement("foo", "http:/foo.bar")
.addText("bar");

OutputFormat format = OutputFormat.createPrettyPrint();
XMLWriter writer = new XMLWriter( System.out, format );
writer.write( document );
}
}



Aucun commentaire:

Enregistrer un commentaire