package dom;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.soap.Node;
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.NodeList;
public class DomTest3
{
public static void praseXml(Element element)
{
String tagName = element.getNodeName();
System.out.print("<" + tagName);
NamedNodeMap attrs = element.getAttributes();
if(null != attrs)
{
for(int i = 0; i < attrs.getLength(); i++)
{
Attr attr = (Attr)attrs.item(i);
System.out.print(" " + attr.getName() + "=" + "\"" + attr.getValue() + "\"");
}
}
System.out.print(">");
NodeList nodeList = element.getChildNodes();
for(int i = 0; i < nodeList.getLength(); i++)
{
if(nodeList.item(i).getNodeType() == Node.TEXT_NODE)
{
System.out.print(nodeList.item(i).getNodeValue());
}
else if(nodeList.item(i).getNodeType() == Node.ELEMENT_NODE)
{
praseXml((Element)nodeList.item(i));
}
else if(nodeList.item(i).getNodeType() == Node.COMMENT_NODE)
{
System.out.print("<!--" + ((Comment)nodeList.item(i)).getData() + "-->");
}
}
System.out.print("</" + tagName + ">");
}
public static void main(String[] args) throws Exception
{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new File("student.xml"));
Element root = doc.getDocumentElement();
praseXml(root);
}
}
|
|