package testxml;
import java.io.File;
import java.io.FileNotFoundException;
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.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class DomXmlTest
{
public static void DomTest(Node node)
{
NodeList books = node.getChildNodes();
for(int i=0;i<books.getLength();i++)
{
Node book = books.item(i);
if(book.getNodeType() == Node.ELEMENT_NODE)
{
if(book.hasAttributes())
{
Element document = (Element)book;
NamedNodeMap docmap = document.getAttributes();
for(int j=0;j<docmap.getLength();j++)
{
Node booktwo = docmap.item(j);
String value = booktwo.getFirstChild().getNodeValue();
System.out.println("attribute="+booktwo.getNodeName()+" "+value);
}
}
if(book.getChildNodes().getLength()==1)
{
String attr = book.getFirstChild().getNodeValue();
System.out.println(book.getNodeName()+": "+attr);
}
else
{
System.out.println(book.getNodeName());
DomTest(book);
}
}
}
}
public static void main(String args[])
{
DocumentBuilderFactory domfac = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder domBuilder = domfac.newDocumentBuilder();
File is = new File("E:/test.xml");
Document doc = domBuilder.parse(is);
DomTest(doc);
}
catch (ParserConfigurationException e)
{
e.printStackTrace();
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
catch(SAXException e)
{
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}