Controlling namespace prefixes in JAXB

前端 未结 5 773
无人及你
无人及你 2020-12-03 12:05

How does jaxb determine the list of namespace prefix declarations whem marshalling an object? I used xjc to compile java classes for ebics (ebics schema). When I create an i

5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-03 12:48

    After crawling many posts, solutions using NamespacePrefixMapper has dependency on JDK version (which may break the code in the future) or the XML DOM tree manipulation looks complicated.

    My brute-force approach is to manipulate the generated XML itself.

    /**
     * Utility method to hide unused xmlns definition in XML root.
     * @param sXML Original XML string.
     * @return
     */
    public static String hideUnUsedNamespace(String sXML) {
        int iLoc0 = sXML.indexOf("?><");
        int iLoc1 = sXML.indexOf("><",iLoc0+3)+1;
        String sBegin = sXML.substring(0,iLoc0+2);
        String sHeader = sXML.substring(iLoc0+2, iLoc1-1);
        String sRest = sXML.substring(iLoc1);
        //System.out.println("sBegin=" + sBegin);
        //System.out.println("sHeader=" + sHeader);
        //System.out.println("sRest=" + sRest);
    
        String[] saNS = sHeader.split(" ");
        //System.out.println("saNS=" + java.util.Arrays.toString(saNS));
    
        StringBuffer sbHeader = new StringBuffer();
        for (String s: saNS) {
            //System.out.println(s);
            if (s.startsWith("xmlns:")) {
                String token = "<" + s.substring(6,s.indexOf("="));
                //System.out.println("token=" + token + ",indexOf(token)=" + sRest.indexOf(token));
                if (sRest.indexOf(token) >= 0) {
                    sbHeader = sbHeader.append(s).append(" ");
                    //System.out.println("...included");
                }
            } else {
                sbHeader = sbHeader.append(s).append(" ");
            }
        }
        return (sBegin + sbHeader.toString().trim() + ">" + sRest);
    }
    
    /**
     * Main method for testing
     */
    public static void main(String[] args) {
        String sXML ="SIZBN001A5488F43223063171CA0FA59ADC635F02009-08-04T08:41:56.967ZEBICSEBIXEBICS-Kernel V2.0.4, SIZ/PPIFTBA037OZHNN......00001InitialisationCSbjPbiNcFqSl6lCI1weK5x1nMeCH5bTQq5pedq5uI0=...dFAYe281vj9NB7w+VoWIdfHnjY9hNbZLbHsDOu76QAE=......";
    
        System.out.println("Before=" + sXML);
        System.out.println("After =" + hideUnUsedNamespace(sXML));
    }
    

    The output shows un-used xmlns namespace is filtered out:

    
    

提交回复
热议问题