package demo;
import org.apache.xerces.parsers.DOMParser;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class XmlDomDemo
{
@Test
public void test()
{
String url = "conf/test/dispatcher-config.xml";
parseAndPrint(url);
}
public void parseAndPrint(String uri)
{
Document doc = null;
try
{
DOMParser parser = new DOMParser();
parser.parse(uri);
doc = parser.getDocument();
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
if (doc != null)
printDomTree(doc);
}
public void printDomTree(Node node)
{
int type = node.getNodeType();
switch (type)
{
case Node.DOCUMENT_NODE:// document类型
System.out.println("<?xml version=\"1.0\" ?>");
printDomTree(((Document)node).getDocumentElement());
break;
case Node.ELEMENT_NODE:// 元素类型
System.out.print("<");
System.out.print(node.getNodeName());
NamedNodeMap attrs = node.getAttributes();
for (int i = 0; i < attrs.getLength(); i++)
{
Node attr = attrs.item(i);
System.out.print(" " + attr.getNodeName() + "=\"" + attr.getNodeValue() + "\"");
}
System.out.print(">");
NodeList children = node.getChildNodes();
if (children != null)
{
int len = children.getLength();
for (int i = 0; i < len; i++)
printDomTree(children.item(i));
}
break;
case Node.ENTITY_REFERENCE_NODE:
System.out.print("&");
System.out.print(node.getNodeName());
System.out.print(";");
break;
case Node.CDATA_SECTION_NODE:
System.out.print("<![CDATA[");
System.out.print(node.getNodeValue());
System.out.print("]]>");
break;
case Node.TEXT_NODE:
System.out.print(node.getNodeValue());
break;
case Node.PROCESSING_INSTRUCTION_NODE:
System.out.print("<?");
System.out.print(node.getNodeName());
String data = node.getNodeValue();
System.out.print(" ");
System.out.print(data);
System.out.print("?>");
break;
}
if (type == Node.ELEMENT_NODE)
{
System.out.print("</");
System.out.print(node.getNodeName());
System.out.print(">");
}
}
}
dom树打印
最新推荐文章于 2024-09-29 15:01:26 发布