Java parsing string string XML multilevel Node NodeList

Source: Internet
Author: User
Tags server port

NodeList subnodelist = Rootnode.getchildnodes ();
for (int i = 0; i < subnodelist.getlength (); i++) {
System.out.println ("Node name of child node:" + Subnodelist.item (i). Getnodename ());
SYSTEM.OUT.PRINTLN (node text content of child nodes: + Subnodelist.item (i). Gettextcontent ());
}


<?xml version= "1.0" encoding= "UTF-8"?> <server port= "8005" shutdown= "Shutdown" >
<service name= "Catalina" >
<Connector> First connector </Connector>
<Connector> a second connector
<open> Open Service </open>
<init> Initialize </init>
<service> Execute Request Service </service>
<destory> Destroy </destory>
<close> Shutdown Services </close>
</Connector>
</Service>
</Server>


public void ParseXml03 () {
try{
Create a Documentbuilder factory instance
Documentbuilderfactory dbf = Documentbuilderfactory.newinstance ();
A new documentbuilder.
Documentbuilder db = Dbf.newdocumentbuilder ();
InputStream InputStream = This.getclass (). getResourceAsStream ("Server03.xml");

Document document = Db.parse (InputStream);
Get the node collection based on the node name
NodeList nodelist = Document.getdocumentelement (). Getchildnodes ();
for (int i = 0; i < nodelist.getlength (); i++) {
Node node = Nodelist.item (i);
if (!) #text ". Equals (Node.getnodename ())) {
System.out.println ("1" "+ node.getnodename () +": "+ node.getfirstchild (). Getnodevalue ());
}
NodeList subnodelist = Node.getchildnodes ();
for (int j = 0; J < Subnodelist.getlength (); j + +) {
Node subnode = Subnodelist.item (j);
if (!) #text ". Equals (Subnode.getnodename ())) {
System.out.println ("2" "+ subnode.getnodename () +": "+ subnode.getfirstchild (). Getnodevalue ());
}
NodeList subsubnodelist = Subnode.getchildnodes ();
for (int k = 0; k < subsubnodelist.getlength (); k++) {
Node Subsubnode = Subsubnodelist.item (k);
if (!) #text ". Equals (Subsubnode.getnodename ())) {
System.out.println ("3" "+ subsubnode.getnodename () +": "+ subsubnode.getfirstchild (). Getnodevalue ());
}
}
}
}
catch (Parserconfigurationexception e) {
E.printstacktrace ();
catch (Saxexception e) {
E.printstacktrace ();
catch (IOException e) {
E.printstacktrace ();
}

}


Next executes the main method of the class, and the console effect is as follows:



<?xml version= "1.0" encoding= "GB2312"?> < Student roster > < student gender = "Male" > < name > Li Hua </name > < age >14</Age > </Student > < student gender = "man" > < name > John </name > < age &G t;16</Age > </student > </Student Roster 
Import Java.io.ByteArrayInputStream;
Import Java.io.ByteArrayOutputStream;
Import Java.io.InputStream;
Import Java.io.OutputStreamWriter;
Import Java.util.Iterator;
Import Java.util.Vector;
Import Javax.xml.parsers.DocumentBuilder;
Import Javax.xml.parsers.DocumentBuilderFactory;
Import Javax.xml.transform.OutputKeys;
Import Javax.xml.transform.Result;
Import Javax.xml.transform.Source;
Import Javax.xml.transform.Transformer;
Import javax.xml.transform.TransformerConfigurationException;
Import javax.xml.transform.TransformerException;
Import Javax.xml.transform.TransformerFactory;
Import Javax.xml.transform.dom.DOMSource;
Import Javax.xml.transform.stream.StreamResult;
Import org.w3c.dom.Document;
Import org.w3c.dom.Element;
Import Org.w3c.dom.Node;
Import org.w3c.dom.NodeList;

Import Org.w3c.dom.Text;

    public class Domtest {Vector students_vector; Private Vector readxmlfile (String file) throws Exception {documentbuilderfactory dbf = documentbuilderfactory.new InstancE ();
        Documentbuilder builder = Dbf.newdocumentbuilder (); Document doc = builder.parse (file); Get to XML file//below start reading Element root = Doc.getdocumentelement ();
        Gets the root element nodelist students = root.getelementsbytagname ("student");
        Students_vector = new Vector (); for (int i = 0; i < students.getlength (); i++) {//once for each student element elements SS = (Element) students

            . item (i);
            Create a student instance student Stu = new Student ();

            Stu.setsex (Ss.getattribute ("gender"));
            NodeList names = ss.getelementsbytagname ("name");
            Element e = (element) names.item (0);
            Node t = e.getfirstchild ();

            Stu.setname (T.getnodevalue ());
            NodeList ages = ss.getelementsbytagname ("Age");
            E = (Element) ages.item (0);
            t = E.getfirstchild ();

            Stu.setage (Integer.parseint (T.getnodevalue ()));
        Students_vector.add (Stu); RetUrn Students_vector; /** * Features: Direct extraction of information in XML format strings * * Private Vector readxmlstring (String xmlstr) throws Exception {D
        Ocumentbuilderfactory dbf = Documentbuilderfactory.newinstance ();
        Documentbuilder builder = Dbf.newdocumentbuilder ();
        InputStream InputStream = new Bytearrayinputstream (Xmlstr.getbytes ()); Document doc = Builder.parse (InputStream); The following starts reading Element root = Doc.getdocumentelement ();
        Gets the root element nodelist students = root.getelementsbytagname ("student");
        Students_vector = new Vector (); for (int i = 0; i < students.getlength (); i++) {//once for each student element elements SS = (Element) students

            . item (i);
            Create a student instance student Stu = new Student ();

            Stu.setsex (Ss.getattribute ("gender"));
            NodeList names = ss.getelementsbytagname ("name");
            Element e = (element) names.item (0);
            Node t = e.getfirstchild (); STu.setname (T.getnodevalue ());
            NodeList ages = ss.getelementsbytagname ("Age");
            E = (Element) ages.item (0);
            t = E.getfirstchild ();

            Stu.setage (Integer.parseint (T.getnodevalue ()));
        Students_vector.add (Stu);
    return students_vector;
            //Writes the Document content to an XML string and returns private string Callwritexmlstring (document DOC, String encoding) {try {
            SOURCE Source = new Domsource (DOC);
            Bytearrayoutputstream OutStream = new Bytearrayoutputstream ();
            OutputStreamWriter write = new OutputStreamWriter (OutStream);

            Result result = new Streamresult (write);
            Transformer Xformer = Transformerfactory.newinstance (). Newtransformer ();

            Xformer.setoutputproperty (outputkeys.encoding, ENCODING);
            Xformer.transform (source, result);

        return outstream.tostring (); catch (Transformerconfigurationexception e) {E.printstacktrace ();
        return null;
            catch (Transformerexception e) {e.printstacktrace ();
        return null; }/** * Features: Generating strings in XML format/public string writexmlstring () {documentbuilderfactory DBF =
        Documentbuilderfactory.newinstance ();
        Documentbuilder builder = null;
        try {builder = Dbf.newdocumentbuilder ();

        catch (Exception e) {} Document doc = Builder.newdocument ();
        Element root = doc.createelement ("Student roster"); Doc.appendchild (root); Add the root element to the document//Get student information for (int i = 0; i < students_vector.size (); i++) {Student S = (st
            udent) Students_vector.get (i);
            Create a student Element Stu = doc.createelement ("student");
            Stu.setattribute ("Gender", S.getsex ());
    Root.appendchild (stu);//Add attribute//Create text name node Element name = Doc.createelement ("name");        Stu.appendchild (name);
            Text tname = Doc.createtextnode (S.getname ());

            Name.appendchild (Tname);
            Create a text Age node Element: doc.createelement ("age"); Stu.appendchild (age);
            Add age to the student node Text Tage = Doc.createtextnode (string.valueof (S.getage ())); Age.appendchild (Tage);
            Place the text node on the age node} try {String result = callwritexmlstring (doc, "gb2312");
        return result;
            catch (Exception e) {e.printstacktrace ();
        return null;
        }/** * Main function/public static void Main (string args[]) {string str = "Xml\\student.xml";
        Domtest t = new domtest ();
        System.out.println ("parsing the original XML file:");
            try {Vector v = t.readxmlfile (str);
            Iterator it = V.iterator ();
                while (It.hasnext ()) {student s = (student) it.next (); System.out.println (s.getname () + "T" + s.getage () + "T" + s.getsex ());

        } catch (Exception e) {e.printstacktrace ();
        String xmlstr = t.writexmlstring ();
        System.out.println ("\ n generated XML string: \ n" + xmlstr);
            try {Vector v = t.readxmlstring (XMLSTR);
            Iterator it = V.iterator ();
            System.out.println ("\ n parse generated XML string:");
                while (It.hasnext ()) {student s = (student) it.next ();
            System.out.println (S.getname () + "T" + s.getage () + "T" + s.getsex ());
        The catch (Exception e) {//TODO auto-generated catch block E.printstacktrace ();
    }} class Student {private String sex;
    private String name;

    private int age;
    public int getage () {return age;
    public void Setage (int age) {this.age = age; public void Setsex (String s) {sex = s;
    Public String Getsex () {return sex;
    public void SetName (String n) {name = N;
    Public String GetName () {return name; }
}

Output:

Parsing the original XML file:
li Hua    man
John

XML string generated:
<?xml version= "1.0" encoding= "GB2312" Standalone= "No"?>< student roster >< Student sex = "male" >< name > Li hua </name >< Age >14</age ></student >< Student sex = "male" >< name > John </name >< Age >16</age ></student ></student roster >

parse generated XML string:
Li Hua    male
John    


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.