Java支持DOM接口,意味着我们可以通过操作通过DOM接口来操作XML,如果你曾经使用过DOM的话,那么这将变得非常简单,因为DOM的接口基本上都是类似的。
先给出需要读的XML文件:
<books>
<book>
<author>Dave Crane</author>
<bookname>Ajax In Action</bookname>
</book></books>
<book>
<author>Ryan Asleson</author>
<bookname>Foundations of Ajax</bookname>
</book>
<author>Dave Crane</author>
<bookname>Ajax In Action</bookname>
</book></books>
<book>
<author>Ryan Asleson</author>
<bookname>Foundations of Ajax</bookname>
</book>
然后我们来看Java如何来操作这个XML文件:
import javax.xml.parsers.*;
import org.w3c.dom.*;
public class domreadxml
{
public static void main(String args[])
{
try
{
DocumentBuilderFactory Factory = DocumentBuilderFactory.newInstance();
DocumentBuilder Builder = Factory.newDocumentBuilder();
Document doc=Builder.parse("book.xml");
doc.normalize();
NodeList books = doc.getElementsByTagName("book");
for (int i=0;i
{
Element book = (Element) books.item(i);
System.out.println(book.getElementsByTagName("author").item(0).getFirstChild().getNodeValue());
System.out.println(book.getElementsByTagName("bookname").item(0).getFirstChild().getNodeValue());
System.out.println("======================");
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
public class domreadxml
{
public static void main(String args[])
{
try
{
DocumentBuilderFactory Factory = DocumentBuilderFactory.newInstance();
DocumentBuilder Builder = Factory.newDocumentBuilder();
Document doc=Builder.parse("book.xml");
doc.normalize();
NodeList books = doc.getElementsByTagName("book");
for (int i=0;i
{
Element book = (Element) books.item(i);
System.out.println(book.getElementsByTagName("author").item(0).getFirstChild().getNodeValue());
System.out.println(book.getElementsByTagName("bookname").item(0).getFirstChild().getNodeValue());
System.out.println("======================");
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
这里我们用到了org.w3c.dom.*;和javax.xml.parsers.*这些类,这些类是JDK默认安装的,在JAVA_HOME/jre/lib/rt.jar这个包里面。这个包还包括了SAT的支持。
DOM和SAT都是XML的解析器,SUN为了取消它们之间的不同,开发出JAXP(Java Api for XML Processing ),通过这个接口我们可以不管底层解析器的区别。关于这个问题,我会专门写一篇文章来介绍。