[JAVA100 example]068, parsing XML with DOM

Source: Internet
Author: User
Tags tag name

import javax.xml.parsers.*;
import org.w3c.dom.*;
import java.io.*;
public class Dompagelist {
public static void Main (string[] args) {
try {
///Create resolution factory
Documentbuilderfactory Dbfactory = Documentbui Lderfactory.newinstance ();    
//Specifies documentbuilder
Documentbuilder builder = Dbfactory.newdocumentbuilder ();
   Constructs a document from a file because the encoding is already specified in the XML file, so there is no need for
Document doc = builder.parse (new File ("Book.xml"));
   Get the root of document (node name: book)
Element root = Doc.getdocumentelement ();
SYSTEM.OUT.PRINTLN ("root node Tag name:" + root.gettagname ());
System.out.println ("traverse the XML element * * *");    
//Get page element
NodeList list = root.getelementsbytagname ("page");
Iterate through the page element
for (int i=0 i < list.getlength (); i++) {
//Get page's Elements
Element element = (Element) Li St.item (i);     
//Get id attribute
String id = element.getattribute ("id");
Gets the title property
NodeList titlelist = Element.geteleMentsbytagname ("title");     
//Obtains title element
Element titleelement = (element) titlelist.item (0);
    Gets the first value of the title element
String title = Titleelement.getfirstchild (). Getnodevalue ();
    Gets the file element name
nodelist filelist = element.getelementsbytagname ("file");
    Gets the file element
Element fileelement = (Element) filelist.item (0);
    Gets the first value of the file element
String file = Fileelement.getfirstchild (). Getnodevalue ();
String test = Filelist.getfirstchild (). Getnodename ();
System.out.println ("id" + ID + "" +
"title" + title +
"file" + file);
}   
} catch (Exception e) {
E.printstacktrace ();
}
}

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.