将命名空间添加到根元素,并为所有子JDOM添加前缀



我试图用JDOM:构建一个xml文档

Node N =Effective_Change.getElementsByTagName("xml-fragment").item(0);
NewElement=N.getOwnerDocument().createElementNS(namespace, N.getNodeName());
Namespace sNS =Namespace.getNamespace(prefix,namespace);
list = N.getChildNodes();
NodeList ListInter=null;
org.jdom.Element subroot=null;
for(int c=1;c<list.getLength();c++) {
if(!(list.item(c).getNodeName().equals("#text"))){
if(list.item(c).getChildNodes().getLength()>1) {
System.out.println("true : "+list.item(c).getChildNodes().getLength());
}
else {
subroot=new org.jdom.Element(list.item(c).getNodeName(), sNS);
subroot.addContent(list.item(c).getTextContent());
}

root.addContent(subroot);
XMLOutputter outp = new XMLOutputter();
String s = outp.outputString(root);
System.out.println(s);
}
}

我的输入xml字符串:

<xml-fragment>
<Derived_Event_Code>xx</Derived_Event_Code>
<Effective_Moment>2018-07-23T04:20:04</Effective_Moment>
<Entry_Moment>2018-07-23T04:20:04</Entry_Moment>
<Person_Identification isUpdated="1">
<Government_Identifier isDeleted="1">
<Government_ID>xxxx</Government_ID>
<Government_ID_Type>xxxx</Government_ID_Type>
<Issued_Date>xxxx</Issued_Date>
</Government_Identifier>
</Person_Identification>
</xml-fragment>

实际输出:

<xml-fragment xmlns="urn:com.uri/peci">
<peci:Derived_Event_Code xmlns:peci="urn:com.workday/peci">DTA</peci:Derived_Event_Code>
<peci:Effective_Moment xmlns:peci="urn:com.workday/peci">2018-07-23T04:20:04</peci:Effective_Moment>
<peci:Entry_Moment xmlns:peci="urn:com.workday/peci">2018-07-23T04:20:04</peci:Entry_Moment>
</xml-fragment>

我想要如下代码所示的输出:仅用于根标记的命名空间,在本例中用于xml片段,对于其余标记,我只需要前缀,不需要名称空间,也不需要子标记的属性xmlns:"。

<xml-fragment xmlns="urn:com.uri/peci">
<peci:Derived_Event_Code>xx</peci:Derived_Event_Code>
<peci:Effective_Moment>2018-07-23T04:20:04</peci:Effective_Moment>
<peci:Entry_Moment>2018-07-23T04:20:04</peci:Entry_Moment>
</xml-fragment>

甚至当我尝试时

subroot.setNamespace(sNS.NO_NAMESPACE);

我得到了子标签属性xmlns:">

我真的需要帮助!!

你的要求没有意义。如果使用名称空间感知解析器解析所需文档,则该文档无效,因为peci前缀没有名称空间声明。如果使用不知道名称空间的解析器对其进行解析,则文档是有效的,但是根元素没有任何名称空间,其他元素也没有,但是它们的本地名称已经更改。

这真的是你想要的吗?

更新

我从您(已删除(的回答中看到,也许您想要的只是更改所有元素的名称空间。在这种情况下,这可能会有所帮助:

... 
Document d = new SAXBuilder().build(...);
updateNamespace(d.getRootElement(), Namespace.getNamespace("peci", "urn:com.uri/peci"));
...
static void updateNamespace(Element e, Namespace ns) {
e.setNamespace(ns);
for(Element child: e.getChildren()) {
updateNamespace(child, ns);
}
}

之后,您可以筛选出结果文档中不需要的元素。

Namespace namespace_xsi = Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
Namespace namespace_ext = Namespace.getNamespace("ext", "urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2");
// create the jdom
Document jdomDoc = new Document();
// create root element
Element rootElement = new Element("Invoice", namespace_xsi);
rootElement.addNamespaceDeclaration(namespace_ext);

最新更新