[Html]
Package WildCat. Xml. Dom;
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. Attr;
Import org. w3c. dom. Comment;
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 testXml1_3 {
/**
* @ Param args
* @ Throws ParserConfigurationException
* @ Throws IOException
* @ Throws SAXException
*/
Public static void main (String [] args) throws ParserConfigurationException, SAXException, IOException {
// Step1. obtain the factory
DocumentBuilderFactory dbf = DocumentBuilderFactory. newInstance ();
// Setp2. get the parser
DocumentBuilder db = dbf. newDocumentBuilder ();
// Step 3 get the Document Object (root node)
Document doc = db. parse (new File ("test. xml "));
// Obtain the root element node
Element root = doc. getDocumentElement ();
ParseElement (root );
}
Public static void parseElement (Element ele)
{
// Get the tag 'sname
String tagName = ele. getNodeName ();
// Get all the children
NodeList children = ele. getChildNodes ();
System. out. print ("<" + tagName );
NamedNodeMap map = ele. getAttributes ();
If (null! = Map)
{
For (int j = 0; j <map. getLength (); j ++)
{
// Downward type conversion
Attr attr = (Attr) map. item (j );
// Obtain the attribute name
String attrName = attr. getNodeName ();
// Obtain the attribute value
String attrValue = attr. getNodeValue ();
System. out. print ("" + attrName + "= \" "+ attrValue + "\"");
}
}
System. out. print ("> ");
For (int I = 0; I <children. getLength (); I ++)
{
Node node = children. item (I );
// Get the node's type
Short nodeType = node. getNodeType ();
If (Node. ELEMENT_NODE = nodeType)
{
// Go on Recursion
ParseElement (Element) node );
}
Else if (Node. TEXT_NODE = nodeType)
{
// If it is text
System. out. print (node. getNodeValue ());
}
Else if (Node. COMMENT_NODE = nodeType)
{
System. out. print ("<! --");
Comment comment = (Comment) node;
// Obtain the comments
String data = comment. getData ();
System. out. println (data + "--> ");
}
}
System. out. print ("</" + tagName + "> ");
}
}
Author: superlele123