gpt4 book ai didi

java - 解析xml文档Java "cannot be resolved"

转载 作者:行者123 更新时间:2023-12-01 14:59:14 24 4
gpt4 key购买 nike

我正在学习如何使用 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);
}
}
}

最佳答案

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

private DocumentBuilder db;

并像这样在parseXmlFile中初始化:

db = dbf.newDocumentBuilder();

关于java - 解析xml文档Java "cannot be resolved",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13921147/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com