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
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 ="SIZBN001 A5488F43223063171CA0FA59ADC635F0 2009-08-04T08:41:56.967Z EBICS EBIX EBICS-Kernel V2.0.4, SIZ/PPI FTB A037 OZHNN ... ... 0000 1 Initialisation CSbjPbiNcFqSl6lCI1weK5x1nMeCH5bTQq5pedq5uI0= ... dFAYe281vj9NB7w+VoWIdfHnjY9hNbZLbHsDOu76QAE= ... ... ";
System.out.println("Before=" + sXML);
System.out.println("After =" + hideUnUsedNamespace(sXML));
}
The output shows un-used xmlns namespace is filtered out: