问题
I would like have this format in xml:
<ns2: test xmlns="url" xmlns:ns2="url2" xmlns:ns3="url3">
....
</ns2: test>
I am using the following code:
Namespace ns= Namespace.getNamespace("url");
Namespace ns2 = Namespace.getNamespace("ns2", "url2");
Namespace ns3= Namespace.getNamespace("ns3", "url3");
SAXBuilder vDocBuilder = new SAXBuilder();
Document vDocument = vDocBuilder.build(File);
System.out.println("Root element " + vDocument.getRootElement().getName());
org.jdom.Element test = new org.jdom.Element("test", ns);
vDocument.setRootElement(test);
vNewRootElement.addNamespaceDeclaration(ns2);
vNewRootElement.addNamespaceDeclaration(ns3);
If I set namespace with:
vNewRootElement.setNamespace(ns3);
Then I get thi:s
<ns2: test xmlns:ns2="url2" xmlns:ns3="url3"> ... </ns2: test>
without the default namespace xmlns="url".
Can anybody tell me why it dosen't work and is there a way to solve this problem?
Thanks, haner
回答1:
The following outputs (to System.out)
<?xml version="1.0" encoding="UTF-8"?>
<ns2:test xmlns:ns2="url2" xmlns="url" xmlns:ns3="url3">Some text</ns2:test>
import java.io.IOException;
import org.jdom.Document;
import org.jdom.JDOMException;
import org.jdom.Namespace;
import org.jdom.output.XMLOutputter;
public class Test {
public static void main(String args[]) throws JDOMException, IOException {
Namespace ns = Namespace.getNamespace("url");
Namespace ns2 = Namespace.getNamespace("ns2", "url2");
Namespace ns3 = Namespace.getNamespace("ns3", "url3");
Document vDocument = new Document();
org.jdom.Element test = new org.jdom.Element("test", ns2);
vDocument.setRootElement(test);
//add "url" default namespace
test.addNamespaceDeclaration(ns);
test.addNamespaceDeclaration(ns2);
test.addNamespaceDeclaration(ns3);
test.addContent("Some text");
//dump output to System.out
XMLOutputter xo = new XMLOutputter();
xo.output(vDocument, System.out);
}
}
you need the line
test.addNamespaceDeclaration(ns);
来源:https://stackoverflow.com/questions/7085503/set-namespace-using-jdom