xml文件树状显示,dom解析
效果如下:
test.xml
|--students
|--student
| |--name
| | |--e
| | |--g:ggggggg
| |--k
| | |--m:mmmm
| |--a
| | |--v:vvvvvvvvv
| |--c
| | |--t
| | |--as:asasas
| |--d:dddddd
| |--b:bbbb
| |--age:20
|--student
|--name:ls
|--a:aaaa
|--c:cccccc
|--d:dddddd
|--b:bbbb
|--age:20
代码如下:
import javax.xml.parsers.*;
import org.w3c.dom.*;import java.io.*;
public class TreeXml
{
private int []is=new int[20] ;
public void walkNode(Node node,int n)
{
NodeList nodeList=node.getChildNodes();
int len=nodeList.getLength();
is[n+1]=(len-1)/2;
switch(node.getNodeType())
{
case Node.DOCUMENT_NODE:
printName(node,n);
nodeList=node.getChildNodes();
n++;
for(int i=0;i<nodeList.getLength();i++)
walkNode(nodeList.item(i),n);
break;
case Node.ELEMENT_NODE:
nodeList=node.getChildNodes();
if(nodeList.getLength()>1)
{
printName(node,n);
n++;
for(int i=0;i<nodeList.getLength();i++)
walkNode(nodeList.item(i),n);
}
else
printNameValue(node,n);
break;
default:break;
}
is[n]--;
n--;
}
public void printNameValue(Node node,int n)
{
for(int i=0;i<n;i++)
System.out.print(is[i]>0?" | ":" ");
System.out.println(" |--"+node.getNodeName()+":"+node.getFirstChild().getNodeValue());
}
public void printName(Node node,int n)
{
for(int i=0;i<n;i++)
System.out.print(is[i]>0?" | ":" ");
System.out.println(" |--"+node.getNodeName());
}
public static void main(String[]args)
{
if(args.length<1)
{
System.out.println("参数错误!");
System.exit(1);
}
System.out.println(args[0]);
try
{
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
DocumentBuilder builder=factory.newDocumentBuilder();
Document doc=builder.parse(new File(args[0]));
new TreeXml().walkNode(doc.getDocumentElement(),1);
}catch(Exception e)
{
System.out.println("错误"+e.getMessage());
}
System.exit(0);
}
}