Java object converted to XML (text content)

Source: Internet
Author: User
Tags cdata

Editor's summary: Converting Java objects to XML files is simple, but converting Java objects to <! [cdata[text content]]> output does not escape the form is very difficult. We all know that in XML elements, "<" and "&" are illegal. "<" generates an error because the parser interprets the character as the beginning of the new element. "&" also generates an error because the parser interprets the character as the beginning of the character entity. Some text, such as JavaScript code, contains a large number of "<" or "&" characters. To avoid errors, you can define your scripting code as CDATA.

CDATA: Under Tag CDATA, all tags, entity references are ignored, and the XML handlers are treated equally as character data, CDATA in the form of the following:

<! [cdata[text content]]>

CDATA The string "]]>" cannot appear in the text content, and CDATA cannot be nested.

The specific implementation process is as follows:

Java Entity classes:

PUBLICCLASSJAVADOCU {

    privateintid;

    private String text;

    Publicint getId () {

        returnid;

    }

    Publicvoid setId (int id) {

        this.id = ID;

    }

    Public String GetText () {

        returntext;

    }

    Publicvoid SetText (String text) {

        this.text = text;

    }

}

Myxppdriver class:

Publicclassmyxppdriver extends Xppdriver {public

    hierarchicalstreamwritercreatewriter (Writer out) {

        Returnnew Myprettyprintwriter (out);

    }

Myprettyprintwriter class:

Publicclassmyprettyprintwriterimplementsextendedhierarchicalstreamwriter {privatefinal QuickWriter writer;

    privatefinal faststack elementstack = new Faststack (16);

 

    Privatefinalchar[] Lineindenter;

    privatebooleantaginprogress;

    privateintdepth;

    Privatebooleanreadyfornewline;

 

    Privatebooleantagisempty;

    privatestaticfinalchar[] AMP = "&". ToCharArray ();

    privatestaticfinalchar[] LT = "<". ToCharArray ();

    privatestaticfinalchar[] GT = ">". ToCharArray ();

    privatestaticfinalchar[] Slash_r = "". ToCharArray ();

    privatestaticfinalchar[] QUOT = "". ToCharArray ();

    privatestaticfinalchar[] APOS = "'". ToCharArray ();

 

    privatestaticfinalchar[] Close = "</". ToCharArray ();

        Publicmyprettyprintwriter (Writer Writer, char[] lineindenter) {this.writer = new Quickwriter (Writer);

    This.lineindenter = Lineindenter; } publicmyprettyprintwriter (Writer Writer, String lineindenter) {thIs (Writer,lineindenter.tochararray ());

    Public Myprettyprintwriter (Printwriterwriter) {This (writer, newchar[] {', '});

    } publicmyprettyprintwriter (Writer Writer) {This (new PrintWriter (Writer));

        @Override publicvoid AddAttribute (Stringkey, String value) {writer.write (');

        Writer.write (key);

        Writer.write (' = ');

        Writer.write (' \ ");

        Writeattributevalue (writer, value);

    Writer.write (' \ ");

        } protectedvoidwriteattributevalue (Quickwriter writer, String text) {int length = Text.length ();

            for (int i = 0; i < length;i++) {char c = text.charat (i);

                Switch (c) {case ' & ': This.writer.write (AMP);

            Break

                Case ' < ': This.writer.write (LT);

            Break

         Case ' > ': This.writer.write (GT);       Break

                Case ' ": This.writer.write (QUOT);

            Break

                Case ' \ ': This.writer.write (APOS);

            Break

                Case ' \ R ': This.writer.write (Slash_r);

            Break

            Default:this.writer.write (c);

        }}} @Override publicvoid Endnode () {depth--;

            if (tagisempty) {writer.write ('/');

            Readyfornewline = false;

            Finishtag ();

        Elementstack.popsilently ();

            }else{Finishtag ();

            Writer.write (Close);

            Writer.write ((String) Elementstack.pop ());

        Writer.write (' > ');

        } Readyfornewline = true;

        if (depth = = 0) {Writer.flush ();

        }} @Override publicvoid SetValue (String text) {readyfornewline = false; Tagisempty = false;

        Finishtag ();

    WRITETEXT (writer, text);

        } protectedvoid WriteText (Quickwriterwriter, String text) {int length = Text.length (); Stringcdataprefix = "<!

 

        [cdata[]; if (!text.startswith (Cdataprefix)) {for (int i = 0; i < length;i++) {char c = Text.chara

                T (i);

                    Switch (c) {case ' & ': This.writer.write (AMP);

                Break

                    Case ' < ': This.writer.write (LT);

                Break

                    Case ' > ': This.writer.write (GT);

                Break

                    Case ' ": This.writer.write (QUOT);

                Break

                    Case ' \ ': This.writer.write (APOS);

                Break

                    Case ' \ R ': This.writer.write (Slash_r); Break;

                Default:this.writer.write (c);  }} else {for (int i = 0; i < length;i++) {char c =

                Text.charat (i);

            This.writer.write (c);

        @Override publicvoid startnode (String name) {Tagisempty = False}}}}

        Finishtag ();

        Writer.write (' < ');

        Writer.write (name);

        Elementstack.push (name);

        Taginprogress = true;

        depth++;

        Readyfornewline = true;

    Tagisempty = true;

        } privatevoid Finishtag () {if (taginprogress) {writer.write (' > ');

        } taginprogress = false;

        if (readyfornewline) {endofline ();

        } Readyfornewline = false;

    Tagisempty = false;

        } protectedvoid EndOfLine () {writer.write (' \ n '); for (int i = 0; i < DEPTh

        i++) {writer.write (lineindenter);

    } publicvoid Flush () {Writer.flush ();

    } publicvoid Close () {writer.close ();

    } @Override publichierarchicalstreamwriter Underlyingwriter () {returnthis; @Override publicvoid startnode (String name, @SuppressWarnings ("Rawtypes") Class arg1) {//TODO Aut

        o-generated Method Stub tagisempty = false;

        Finishtag ();

        Writer.write (' < ');

        Writer.write (name);

        Elementstack.push (name);

        Taginprogress = true;

        depth++;

        Readyfornewline = true;

    Tagisempty = true; 
 }

}

Java Test class:

publicclassjavadocutest {publicstaticvoid main (string[] args) throws ioexception,jaxbexception {Long T1

        = System.currenttimemillis (); Stringcdataprefix = "<!

        [cdata[];

        Stringcdatabackfix = "]]>";

        JAVADOCUJAVADOCU = NEWJAVADOCU ();

        JavaDocujavadocu2 = NEWJAVADOCU ();

        Javadocu.settext (cdataprefix+ "This is a test" + cdatabackfix);

        Javadocu2.settext (cdataprefix+ "This is another test" + cdatabackfix);

        List<javadocu>list = newarraylist<javadocu> ();

        List.add (JAVADOCU);

        List.add (JAVADOCU2);

        Xstreamxstream = Newxstream (Newmyxppdriver ());

            for (int i = 0; I <list.size (); i++) {list.get (i) setId (i);

            Xstream.alias ("Javatoxml", Javadocu.class);

            Xstream.useattributefor (Javadocu.class, "id");

        Xstream.useattributefor ("id", string.class);

        } System.out.println (Xstream.toxml (list)); Xstream.toxml (list, new PrinTwriter ("c:\\ test. xml", "Utf-8")); }

}

The above code can be implemented to convert JavaBean to include <! [cdata[text content]]> XML file.

Warm tip: This process uses Xstream.1.3.1.jar, please download the required Jar Pack (free) to http://download.csdn.net/detail/yaohucaizi/5120422.

This article original Yhcz due to the summary process is not easy to reprint, please indicate the source, thank you.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.