java dom

2014-11-24 01:42:29 · 作者: · 浏览: 0

First, Build a DocumentBuilderFactory, since is protected ,we have to apply newInstence()

Second, Give the factory an order, the order is DocumentBuilder

Third, find the root node (document)

package DomTest;

import java.io.File;

import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;

import javax.xml.parsers.DocumentBuilderFactory;

import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;

import org.w3c.dom.Element;

import org.w3c.dom.NodeList;

import org.xml.sax.SAXException;

public class DOMTest1

{

public static void main(String[] args) throws SAXException, IOException

{

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

try

{

DocumentBuilder db = dbf.newDocumentBuilder();

Document document = db.parse(new File("student.xml"));

NodeList list = document.getElementsByTagName("student");

System.out.println(list.getLength());

for (int i = 0; i

{

Element element = (Element)list.item(i);

String str = element.getElementsByTagName("name").item(0).getFirstChild().getNodeva lue();

System.out.println(str);

}

}

catch (ParserConfigurationException e)

{

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

XML:

< xml version="1.0" encoding="UTF-8" >

xsi:noNamespaceSchemaLocation="student.xsd">

265153

Lily

28

265953

Tom

28

本文出自 “笨鸟先飞” 博客