我正在尝试使用 JaxB (Jaxb2Marshaller) 将 Java 对象解析为 Xml 表示。在其中一个元素中,我有两个命名空间和几个属性。一切都很好,但首先我得到了属性,然后是命名空间。
如何更改,或者甚至可以更改顺序,所以首先我有 namespace ,然后是所有属性。
我现在所拥有的
<Element elementId="AB000000011" timeStamp="2018-12-04T18:48:52.535+02:00" version="2.0" xmlns="http://www.namespace.com/schemas/namespaceapi" xmlns:ns2="http://www.w3.org/2000/09/xmldsig#">
我想要达到的目标
<Element xmlns="http://www.namespace.com/schemas/namespaceapi" xmlns:ns2="http://www.w3.org/2000/09/xmldsig#" elementId="AB000000011" timeStamp="2018-12-04T18:48:52.535+02:00" version="2.0" >
当然我可以在@XmlType#propOrder 的帮助下管理属性的顺序,但是用命名空间做类似事情的方法是什么?
最佳答案
我不知道如何更改订单,但您可以使用您拥有的内容生成一个全新的 xml 文件并选择您的订单。
DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder();
Document document = documentBuilder.newDocument();
// Root Element
Element root = document.createElement("Element");
document.appendChild(root);
// xmlns Element
Element xmlns = document.createElement("");
root.appendChild(xmlns);
// xmlns2 Element
Element xmlns2 = document.createElement("xmlns:ns2");
root.appendChild(xmlns2);
// Id Element
Element elementId = document.createElement("elementId");
root.appendChild(elementId);
// timeStamp Element
Element timeStamp = document.createElement("timeStamp");
root.appendChild(timeStamp);
// Version Element
Element version = document.createElement("version");
root.appendChild(version);
比您可以使用 Xpath 或 Xstream 设置值(我不知道这是否是正确的名称),如下所示:
// Version Element
Element estruturas = document.createElement("version");
root.appendChild(version);
version.setTextContent(xpathElement(document, "/Element*[@class='version']").getTextContent());
希望我能帮到你。
关于java - Xml Jaxb 命名空间和属性顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53617971/