分类: Java
2007-12-02 11:40:08
程序输出
Root element of the doc is book
Total no of people: 3
First Name: Kiran
Last Name: Pai
Age: 22
First Name: Bill
Last Name: Gates
Age: 46
First Name: Steve
Last Name: Jobs
Age: 40
程序清单
import java.io.File;
import org.w3c.dom.Document;
import org.w3c.dom.*;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class ReadAndPrintXMLFile{
public static void main (String argv []){
try {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse (new File("book.xml"));
// normalize text redivsentation
doc.getDocumentElement ().normalize ();
System.out.println ("Root element of the doc is " + doc.getDocumentElement().getNodeName());
NodeList listOfPersons = doc.getElementsByTagName("person");
int totalPersons = listOfPersons.getLength();
System.out.println("Total no of people : " + totalPersons);
for(int s=0; s //------- NodeList textFNList = firstNameElement.getChildNodes(); //------- NodeList textLNList = lastNameElement.getChildNodes(); //---- NodeList textAgeList = ageElement.getChildNodes(); //------ }//end of if clause }//end of for loop with s var } } } } 作者简介: Kiran Pai,4~5年的开发经历,22岁 (年轻有为啊,我加的),擅长Web开发。
Node firstPersonNode = listOfPersons.item(s);
if(firstPersonNode.getNodeType() == Node.ELEMENT_NODE){
Element firstPersonElement = (Element)firstPersonNode;
NodeList firstNameList = firstPersonElement.getElementsByTagName("first");
Element firstNameElement = (Element)firstNameList.item(0);
System.out.println("First Name : " +
((Node)textFNList.item(0)).getNodeValue().trim());
NodeList lastNameList = firstPersonElement.getElementsByTagName("last");
Element lastNameElement = (Element)lastNameList.item(0);
System.out.println("Last Name : " +
((Node)textLNList.item(0)).getNodeValue().trim());
NodeList ageList = firstPersonElement.getElementsByTagName("age");
Element ageElement = (Element)ageList.item(0);
System.out.println("Age : " + ((Node)textAgeList.item(0)).getNodeValue().trim());
catch (SAXParseException err) {
System.out.println ("** Parsing error" + ", line "
+ err.getLineNumber () + ", uri " + err.getSystemId ());
System.out.println(" " + err.getMessage ());
catch (SAXException e) {
Exception x = e.getException ();
((x == null) ? e : x).printStackTrace ();
catch (Throwable t) {
t.printStackTrace ();
}
//System.exit (0);
}//end of main