我正在阅读有关如何使用java解析xml文档并遇到问题的教程。我收到错误“dom无法解决”我知道它与我声明变量和超出范围的方式有关但我无法弄清楚如何解决它。
非常感谢任何帮助,我将在下面发布相关部分:
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);
}
}
}
答案 0 :(得分:1)
当您在不同方法中使用DocumentBuilder
db
时,您可以将db
声明为类成员变量:
private DocumentBuilder db;
并在parseXmlFile
中进行初始化:
db = dbf.newDocumentBuilder();
答案 1 :(得分:0)
您可以像下面一样更改方法签名,并在调用它时传递创建的文档构建器实例。
private void parseDocument(DocumentBuilder db)