java dom
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<list.getLength(); i++)
{
Element element = (Element)list.item(i);
String str = element.getElementsByTagName("name").item(0).getFirstChild().getNodeValue();
System.out.println(str);
}
}
catch (ParserConfigurationException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
XML:
<?xml version="1.0" encoding="UTF-8"?>
<studentsList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="student.xsd">
<student>
<stuId>265153</stuId>
<name>Lily</name>
<age>28</age>
</student>
<student>
<stuId>265953</stuId>
<name>Tom</name>
<age>28</age>
</student>
</studentsList>
本文出自 “笨鸟先飞” 博客
补充:软件开发 , Java ,