日期:2014-05-20  浏览次数:20707 次

解析xml,求解
// 得到DOM解析器的工厂实例
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
 
// 从DOM工厂获得DOM解析器
DocumentBuilder builder=factory.newDocumentBuilder();
 
// 把要解析的XML文档转化为输入流,以便DOM解析器解析它
InputStream is = new ByteArrayInputStream(retStr.toString().getBytes("UTF-8"));
 
// 解析XML文档的输入流,得到一个Document
Document doc=builder.parse(is);
doc.normalize();
 
// 得到XML文档的根节点(books)
org.w3c.dom.Element root = doc.getDocumentElement();
 
//获得根节点的所有属性名和值
if(0 < root.getAttributes().getLength()){
for(int a = 0; a < root.getAttributes().getLength(); a++){
System.out.println("根节点属性信息"+root.getAttributes().item(a).getNodeName()
+ "---" + root.getAttributes().item(a).getNodeValue());
}
}else{
System.out.println("节点无属性值");
}
 
NodeList recordInfo = doc.getElementsByTagName("fieldInfo");
System.out.println("///////////////////////////////////////");
 
//获得fieldInfo节点属性值和名
for(int i=0;i<recordInfo.getLength();i++){
Element fieldInfo=(Element) recordInfo.item(i);
if(0 < fieldInfo.getAttributes().getLength()){
for(int a = 0; a < fieldInfo.getAttributes().getLength(); a++){
System.out.println("fieldInfo根节点属性信息.........."+fieldInfo.getAttributes().item(a).getNodeName()
+ "---" + fieldInfo.getAttributes().item(a).getNodeValue());
}
}else{
System.out.println("节点无属性");
}
}
 
System.out.println("============================================="); 

//System.out.print("URL: ");
System.out.println(fieldInfo.getElementsByTagName("url").item(0).getFirstChild().getNodeValue());


写一个解析xml的代码的时候红色部分的fieldInfo提示“fieldInfo cannot be resolved”,这是什么原因呢?

------解决方案--------------------
变量fieldInfo 超出作用域范围了,你在上面的大括号内打印吧
------解决方案--------------------
你的fieldInfo是在for循环中声明的,生命周期仅限于for循环内,最后那句System.out.println(fieldInfo.getElementsByTagName("url").item(0).getFirstChild().getNodeValue());
已经超出for循环体了,当然不能访问到fieldInfo对象,所以提示你fieldInfo不能被解析