Java basics-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:/*** located in the root directory of the C drive * ABC. xml **/& lt? XML version = "1.0" encoding = "gb2312 "? & Gt
& Lt messages & gt
& Lt message id = "jhgjg" & gt
& Lt Title & gtjhgjg & lt/Title & gt
& Lt content & gtjhgjg & lt/content & gt
& Lt email & gtjhjh & lt/Email & gt
& Lt/message & gt
& Lt message id = "fdsa" & gt
& Lt Title & gtfdsa & lt/Title & gt
& Lt content & gtfasdf & lt/content & gt
& Lt email & gtfsadfa & lt/Email & gt
& Lt/message & gt
& Lt/messages & gt, 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 child nodes under the root node into the list for (INT I = 0; I <> system. out. println ("---------------------------"); element item = (element) list. get (I); // get the node instance string name = item. getattribute ("name"). getvalue (); // obtain the attribute value system. out. println ("name -->" + name );
Element sub = item. getchild ("title"); // get the byte of the current node
String text = sub. gettext (); // obtain 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.