Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent xml transformer to transform empty tags into single tag

I'm using javax.xml.transform.Transformer class to transform the DOM source into XML string. I have some empty elements in DOM tree, and these become one tag which I don't want.

How do I prevent <sampletag></sampletag> from becoming <sampletag/>?

like image 940
mosahin Avatar asked Sep 20 '10 13:09

mosahin


4 Answers

I tried below to prevent transform empty tags into single tag :

Transformer tf = TransformerFactory.newInstance().newTransformer(); tf.setOutputProperty(OutputKeys.METHOD,"html")

It's retaining empty tags.

like image 107
Komal Avatar answered Nov 03 '22 05:11

Komal


I hade the same problem. This is the function to get that result.

public static String fixClosedTag(String rawXml){

    LinkedList<String[]> listTags = new LinkedList<String[]>(); 
    String splittato[] =  rawXml.split("<");

    String prettyXML="";

    int counter = 0;
    for(int x=0;x<splittato.length;x++){
        String tmpStr = splittato[x];
        int indexEnd = tmpStr.indexOf("/>");
        if(indexEnd>-1){
            String nameTag = tmpStr.substring(0, (indexEnd));
            String oldTag = "<"+ nameTag +"/>";
            String newTag = "<"+ nameTag +"></"+ nameTag +">";
            String tag[]=new String [2];
            tag[0] = oldTag;
            tag[1] = newTag;
            listTags.add(tag);
        }
    }
    prettyXML = rawXml;

    for(int y=0;y<listTags.size();y++){
        String el[] = listTags.get(y);

        prettyXML = prettyXML.replaceAll(el[0],el[1]);
    }

    return prettyXML;
}
like image 40
menna82 Avatar answered Nov 03 '22 05:11

menna82


If you want to control how XML is formatted, provide your own ContentHandler to prettify XML into "text". It should not matter to the receiving end (unless human) whether it receives <name></name> or <name/> - they both mean the same thing.

like image 32
Tom Hawtin - tackline Avatar answered Nov 03 '22 05:11

Tom Hawtin - tackline


The two representations are equivalent to an XML parser, so it doesn't matter.

If you want to process XML with anything else than an XML-parser, you will end up with a lot of work and an XML-parser anyway.

like image 24
Thorbjørn Ravn Andersen Avatar answered Nov 03 '22 03:11

Thorbjørn Ravn Andersen