我正在阅读关于如何使用java解析xml文档并遇到问题的教程。我收到错误“dom无法解决”我知道这与我声明变量并超出范围的方式有关,但我无法弄清楚如何解决它。解析xml文档Java“无法解析”
任何帮助将不胜感激,我会发布的相关部分如下:
package com.xmlparse;
import java.io.IOException;
import java.util.Iterator;
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.NodeList;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import com.entities.Employee;
public class XmlParser
{
private void parseXmlFile(){
//get the factory
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
//Using factory get an instance of document builder
DocumentBuilder db = dbf.newDocumentBuilder();
//parse using builder to get DOM representation of the XML file
Document dom = db.parse("test.xml");
} catch(ParserConfigurationException pce) {
pce.printStackTrace();
} catch(SAXException se) {
se.printStackTrace();
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
private void parseDocument() {
Document dom = db.parse("test.xml");
//get the root element
Element docEle = dom.getDocumentElement();
//get a nodelist of elements
NodeList nl = docEle.getElementsByTagName("Employee");
if(nl != null && nl.getLength() > 0) {
for(int i = 0 ; i < nl.getLength(); i++) {
//get the employee element
Element el = (Element)nl.item(i);
//get the Employee object
Employee e = getEmployee(el);
//add it to list
myEmpls.add(e);
}
}
}
该代码似乎不完整+您说什么样的错误?编译错误?运行时错误? (我认为它是从错误信息编译的 - 如果是的话,哪一行有编译问题?) – RonK
我试图修复错误,它在try块中超出了范围。是的,我没有发布所有的代码。基本上我试图学习如何解析一个XML文档,并抓住与每个标签相关联的文本,并将这些属性放置在一个对象中。下一步将会弄清楚如何通过http请求传递这个消息,但我还没有做到这一点。到目前为止,我已经能够识别对象的数量,但是当我尝试将属性打印到控制台时,每个值都会得到“空值”。如果有人有任何意见,将不胜感激。 – parchambeau