java 使用 jdom 设置命名空间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7085503/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 18:33:59 来源:igfitidea点击:
Set namespace using jdom
提问by haner
I would like have this format in xml:
我想在 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
然后我得到这个: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
谢谢,哈尔
回答by reevesy
The following outputs (to System.out)
以下输出(到 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);