java 解析xml

package com.parse;   

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

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;

  
  
public class XmlReader {   
    public static void main(String[] args) {   
        XmlReader reader = new XmlReader();   
    }   
    
    public static byte[] readFile(String fileName) {
		File file = new File(fileName);
		if (!file.exists() || file.length() == 0)
			return null;

		try {
			FileInputStream in = new FileInputStream(file);
			int total = (int) file.length();
			byte[] b = new byte[total];
			int ret = 0;
			int read = 0;
			while (read < total) {
				ret = in.read(b, read, total - read);
				if (ret < 0)
					break;
				read += ret;
			}
			in.close();
			return b;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
    
    public XmlReader() {
    	byte[] bs = null;
  	  bs = readFile("D://test1.xml");
  	  DocumentBuilder builder;
        try {   
        	DocumentBuilderFactory f = DocumentBuilderFactory.newInstance(); 
			builder = f.newDocumentBuilder();
			InputStream in = new ByteArrayInputStream(bs);
			Document doc = builder.parse(in);
			Element root = doc.getDocumentElement();
			NodeList nodelist = root.getChildNodes();
			for(int i=0; i<nodelist.getLength(); i++){
				Node et = (Node)nodelist.item(i);
				String tagName = et.getNodeName();
				if(tagName.equalsIgnoreCase("Layout")){
					NamedNodeMap map = et.getAttributes();
					Node nd = map.getNamedItem("id");
					if(nd != null){
						System.out.println(nd.getNodeValue());
					}
					
					NodeList childs = et.getChildNodes();
					for (int j = 0; j < childs.getLength(); j++) {
						Node child = (Node)childs.item(j);
						if(child.getNodeName().equalsIgnoreCase("Link")){
							NamedNodeMap attrs = child.getAttributes();
							Node item = attrs.getNamedItem("url");
							if(item != null)
								System.out.println(item.getNodeValue());
						}
					}
					
				}
			}
			in.close();
        } catch (Exception e) {   
            // TODO Auto-generated catch block   
            e.printStackTrace();   
        }   
  }
}  


<Backgroud>
	<Layout id="thumbnail">
		<Link url="hy" />
	</Layout>
</Backgroud>


<pre name="code" class="html">

                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值