Use JDOM to read and write XML files

Source: Internet
Author: User

The simplest way to understand JDOM is Java + xml = JDOM. The following is an example of simple XML operations.

1. The following is an XML file used in the example:

/**

* In the C-drive root directory

* ABC. xml

**/

<? XML version = "1.0" encoding = "gb2312"?>
<Messages>
<Message id = "jhgjg">
<Title> jhgjg </title>
<Content> jhgjg </content>
<Email> jhsf-</Email>
</Message>
<Message id = "fdsa">
<Title> fdsa </title>
<Content> fasdf </content>
<Email> fsadfa </Email>
</Message>
</Messages>

2. xml operating program

/**

* Myjdom. Java

**/

Package com. test;
Import org. JDOM .*;
Import org. JDOM. Input .*;
Import org. JDOM. Output .*;

Import java. Io. fileinputstream;
Import java. Io. fileoutputstream;
Import java. util. List;

Public class myjdom {

Public static void main (string [] ARGs) throws exception {
Saxbuilder sb = new saxbuilder (); // create a constructor
Document Doc = sb. Build (New fileinputstream ("C: // ABC. xml"); // read the specified file

Element root = Doc. getrootelement (); // obtain the root node
List list = root. getchildren (); // put all the subnodes under the root node into the list

For (INT I = 0; I <list. Size (); I ++ ){

System. Out. println ("---------------------------");

Element item = (element) list. Get (I); // get the node instance

String name = item. getattribute ("name"). getvalue (); // get the attribute value

System. Out. println ("name -->" + name );

Element sub = item. getchild ("title"); // get the byte of the current node
String text = sub. gettext (); // gets the value of the current node.

System. Out. println ("title -->" + text );

Element sub2 = item. getchild ("content ");
String text2 = sub2.gettext ();

System. Out. println ("content -->" + text2 );

Element sub3 = item. getchild ("email ");
String text3 = sub3.gettext ();

System. Out. println ("email -->" + text3 );
}
}
}

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.