0

我正在阅读有关如何使用 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);
        }
    }
}
4

2 回答 2

1

当您DocumentBuilder db在不同的方法中使用时,您可以声明db为类成员变量:

private DocumentBuilder db;

并像这样初始化parseXmlFile

db = dbf.newDocumentBuilder();
于 2012-12-17T19:53:36.963 回答
0

您可以像下面这样更改方法签名,并在调用它时传递创建的文档构建器实例。

private void parseDocument(DocumentBuilder db) 
于 2012-12-17T19:58:58.467 回答