黑马程序员技术交流社区
标题:
以dom方式解析一个xml文档并将其格式化输出到控制台
[打印本页]
作者:
天地有我
时间:
2013-9-1 19:06
标题:
以dom方式解析一个xml文档并将其格式化输出到控制台
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);
}
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2