1.
public class abc
{
public static void main(String[] args)
{
StringBuffer ss = new StringBuffer();
        ss.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        ss.append("<Message>");
        ss.append("   <item lib=\"area\" bdate=\"2007-08-25 13:36:23\" edate=\"2007-08-30 13:36:23\" />");
        ss.append("</Message>");        String content = ss.toString();
        System.out.println(content);
DomParse.parse(content);
}}2.import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;public class DomParse
{
public static void parse(String str)
{
String s = str.replaceAll("UTF-8", "gb2312");// 替换为gb2312,可以支持中文
byte[] b = s.toString().getBytes();
InputStream ip = new ByteArrayInputStream(b);
//得到DOM解析器的工厂实例
DocumentBuilderFactory domfac = DocumentBuilderFactory.newInstance(); 
try
{
//从DOM工厂获得DOM解析器
DocumentBuilder dombuilder = domfac.newDocumentBuilder();
//解析XML文档的输入流,得到一个Document
Document doc = dombuilder.parse(ip);
//得到XML文档的根节点
Element root = doc.getDocumentElement();
//得到节点的子节点
NodeList smss = root.getChildNodes();
if (smss != null)
{
int length = smss.getLength();
for (int i = 0; i < smss.getLength(); i++)
{
Node sms = smss.item(i);
Node node = sms.getFirstChild();
if(node != null)
{
System.out.println("node != null");
}
else if(node == null)
{
System.out.println("node == null");
}
for (; node != null; node = node
.getNextSibling())
{
if (node.getNodeType() == Node.ELEMENT_NODE)
{
if (node.getNodeName().equals("item"))
{
String mobile = node.getAttributes()
.getNamedItem("lib").getNodeValue();
System.out.println("lib:" + mobile);
}
}
}
}
}
} catch (ParserConfigurationException e)
{
e.printStackTrace();
} catch (SAXException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}

}
}为什么我 的 解析不出来呢  
高手给我找找问题啊
我找了 半天了

解决方案 »

  1.   

    Node sms = smss.item(i);
    Node node = sms.getFirstChild();把这段代码修改如下:
    //Node sms = smss.item(i);
    //Node node = sms.getFirstChild();
    Node node=smss.item(i);
    if (node.getNodeType() != Node.ELEMENT_NODE) continue;
      

  2.   

    Node sms = smss.item(i);
    //sms的到的是item节点的信息信息
    Node node = sms.getFirstChild();
    //item节点的孩子信息,有吗,没有所以直接Node node=smss.item(i);取得item节点同时XML DOM树中可能存在一些空的text节点,所以必须加入判断:
    if (node.getNodeType() != Node.ELEMENT_NODE) continue;
    以防止对空的节点也进行操作Understand?