现在的位置: 首页 > 综合 > 正文

Java 解析 XML

2018年02月06日 ⁄ 综合 ⁄ 共 1168字 ⁄ 字号 评论关闭
  • DOM方式
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    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;
    /**
     * 
     * @author WalkingDog
     *
     */
    public class ReadXML
    {
    	public static void main(String[] args)
    	{
    		new ReadXML().readXML("E:/input.xml");
    	}
    	private void readXML(String uri)
    	{
    		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    		DocumentBuilder builder = null;
    		Document document = null;
    		try
    		{
    			builder = factory.newDocumentBuilder();
    			document = builder.parse(uri);
    		}
    		catch (Exception e)
    		{
    			e.printStackTrace();
    			factory = null;
    		}
    		Element root = document.getDocumentElement();
    		readNode(root);
    	}
    	private void readNode(Node node)
    	{
    		
    		if(!node.hasChildNodes())
    		{
    			System.out.print(node.getTextContent());
    			return;
    		}
    		StringBuffer buf = new StringBuffer();
    		if(node.hasAttributes())
    		{
    			NamedNodeMap map = node.getAttributes();
    			int len = map.getLength();
    			for(int i = 0; i < len; i++)
    			{
    				Node n = map.item(i);
    				buf.append(" " + n.getNodeName() + "=\"" + n.getNodeValue() + "\"");
    			}
    		}
    		System.out.print("<" + node.getNodeName() + buf + ">");
    		NodeList list = node.getChildNodes();
    		int length = list.getLength();
    		for(int i = 0; i < length; i++)
    		{
    			Node n = list.item(i);
    			readNode(n);
    		}
    	}
    }

  • SAX方式

抱歉!评论已关闭.