【发布时间】:2014-01-21 09:48:43
【问题描述】:
我尝试将 XML 解析数据添加到 DefaultTableModel 中。 DefaultTableModel 根据文档接受 Vectors 或 Object[] 作为参数。
但是当我使用 Vector 时,我得到了这个异常:
java.lang.ClassCastException: java.lang.String cannot be cast to java.util.Vector
这是我用来解析并添加到向量中的类。
public class PropXMLParsing {
static PropXMLParsing instance = null;
private Vector<String> header = new Vector<String>();
private Vector<String> data = new Vector<String>();
public static PropXMLParsing getInstance() {
if (instance == null) {
instance = new PropXMLParsing();
try {
instance.ParserForObjectTypes();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
}
return instance;
}
public void ParserForObjectTypes() throws SAXException, IOException,
ParserConfigurationException {
try {
FileInputStream file = new FileInputStream(new File(
"xmlFiles/CoreDatamodel.xml"));
DocumentBuilderFactory builderFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document xmlDocument = builder.parse(file);
XPath xPath = XPathFactory.newInstance().newXPath();
String expression = "//prop/*";
NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(
xmlDocument, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
System.out.println(nodeList.item(i).getFirstChild()
.getNodeValue());
data.addElement(nodeList.item(i).getFirstChild().getNodeValue());
header.addElement(nodeList.item(i).getFirstChild()
.getNodeValue());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (XPathExpressionException e) {
e.printStackTrace();
}
}
public Vector<String> getHeader() {
return header;
}
public Vector<String> getData() {
return data;
}
}
最后一行代码是它抛出异常的地方。这是来自我的 GUI 类:
model = new DefaultTableModel(PropXMLParsing.getInstance().getHeader(),
PropXMLParsing.getInstance().getData());
table = new JTable(model);
请帮帮我
【问题讨论】:
-
旁注:向您的问题添加异常时,最好标记出抛出异常的行。
标签: java user-interface xpath vector xml-parsing