Java and XML (ii) write XML reading and writing programs in Java

Source: Internet
Author: User

This is to read the XML file Java program, I debug good. The DOM method is used to read the XML file into the vector.

Package src;
Import java.io.*;
Import Java.util.Vector;
Import javax.xml.parsers.*;
Import org.w3c.dom.*;
public class ReadXml {
static document document;
private Boolean validating;
Public ReadXml () {
}
Public Vector toread (String filename) {
Vector title=new vector ();
Vector content=new vector ();
String Mystr=new string ();
try {
Documentbuilderfactory factory = Documentbuilderfactory.newinstance ();
Factory.setvalidating (validating);
Documentbuilder builder = Factory.newdocumentbuilder ();
Document = Builder.parse (new File (filename));
Document.getdocumentelement (). normalize ();
Node node = Document.getfirstchild ();
NodeList list = Node.getchildnodes ();
for (int i = 0; i < list.getlength (); i++) {
Node nodeitm = List.item (i);
if (Nodeitm.getnodename (). Equals ("Title")) {
Mystr=nodeitm.getfirstchild (). Getnodevalue ();
Title.addelement (MYSTR);//getfirstchild ()
}
if (Nodeitm.getnodename (). Equals ("Content")) {
Mystr=nodeitm.getfirstchild (). Getnodevalue ();
Content.addelement (MYSTR);
}
}
catch (Exception exp) {
Exp.printstacktrace ();
return null;
}
Vector all=new vector ();
All.add (title);
All.add (content);
return all;
}

public static void Main (string[] args) {
Vector A;
ReadXml my = new ReadXml ();
A = My.toread ("F:\\tomcat5\\webapps\\myxml\\xmldata\\9.xml");
for (int i = 0; i < a.size (); i++) {
System.out.println (A.elementat (i));
}
}
}

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.