Dom解析xml小程序

来源:互联网 发布:淘宝tbc卖家是什么意思 编辑:程序博客网 时间:2024/06/14 20:47

Dom解析xml

(用Dom解析xml并以原样输出)

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.获得工厂DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();//setp2.获得解析器DocumentBuilder db=dbf.newDocumentBuilder();//step3获得Document对象(根节点)Document doc=db.parse(new File("test.xml"));//获得根元素节点Element root=doc.getDocumentElement();parseElement(root);}public static void parseElement(Element ele){//get the tag'sNameString tagName=ele.getNodeName();//获得所有的孩子NodeList children=ele.getChildNodes();System.out.print("<"+tagName);NamedNodeMap map=ele.getAttributes();if (null!=map){for (int j=0;j<map.getLength();j++){//向下类型转换Attr attr=(Attr)map.item(j);//获得属性名String attrName=attr.getNodeName();//获得属性值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 typeshort nodeType=node.getNodeType();if (Node.ELEMENT_NODE==nodeType){//go on 递归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;//获得注释的内容String data=comment.getData();System.out.println(data+"-->");}}System.out.print("</"+tagName+">");}}


 

原创粉丝点击