有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Xml Jaxb名称空间和属性顺序

我正在尝试使用JaxB(Jaxb2Marshaller)将Java对象解析为Xml表示。在其中一个元素中,我有两个名称空间和几个属性。一切都很好,但首先我得到了属性,然后是名称空间。 如何更改,或者甚至可以更改顺序,所以首先我有名称空间,然后是所有属性

我现在有什么

    <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来管理属性的顺序,但是如何处理名称空间的类似操作呢


共 (1) 个答案

  1. # 1 楼答案

    我不知道如何更改订单,但您可以使用现有的内容生成一个全新的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());
    

    希望我能帮助你