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">