Case of how to parse a string in XML format
/*
* Date Created 2008-4-15
*
* TODO to change the template for this generated file, go to the
* Windows-Preferences-Java-code styles-code templates
*/
Package Com.tsinghua;
Import java.io.*;
Import Javax.xml.parsers.DocumentBuilderFactory;
Import javax.xml.parsers.*;
Import org.w3c.dom.*;
/**
* @author Administrator
*
* TODO to change the template for this generated type annotation, go to the
* Windows-Preferences-Java-code styles-code templates
*/
public class Dome2 {
public static void Main (string[] args) {
Start parsing person.xml files
1 Parser Factory class
Documentbuilderfactory dbf=documentbuilderfactory.newinstance ();
try {
Create a parser from the parser factory
Documentbuilder Db=dbf.newdocumentbuilder ();
Tell the change parser to parse the file-->dom tree
Document dm=db.parse ("F://person.xml");
Parsing the string
String teststr= "<?xml version=/" 1.0/"encoding=/" gb2312/"?>" +
"<!--the XML stores the people information-->" +
"<company><person sex=/" male/"id=/" 0001/"><name att=/" ok/"><realname> small </realname> "+
"<nickname> Piggy </nickname></name><email>zhangsan@sohu.com</email></person> </company> ";
Convert this string to InputStream stream
InputStream istream=new Bytearrayinputstream (Teststr.getbytes ());
Document Dm=db.parse (IStream);
Get all person nodes
NodeList persons=dm.getelementsbytagname ("person");
for (int i=0;i<persons.getlength (); i++) {
Element and node are the same concept
The difference is that the element provides more methods
Element personelement = (Element) persons.item (i);
Get the properties of the person node
String Id=personelement.getattribute ("id");
System.out.println ("id=" +id);
NodeList namelist=personelement.getelementsbytagname ("name");
Element name= (Element) Namelist.item (0);
String att=name.getattribute ("att");
System.out.println ("att=" +att);
Remove the value of name
System.out.println ("name=" +namelist.item (0). Getfirstchild (). Getnodevalue ());
}
catch (Exception e) {
Todo:handle exception
E.printstacktrace ();
finally {
}
}
}