我编写了一个可以将数据保存到xml中的代码。现在我想使用存储的xml并将其数据导入我在表单中的表中。问题是:代码没有错误,但表不是xml数据的字段:( 这是我的代码:
private void jPanel4ComponentShown(java.awt.event.ComponentEvent evt) {
// TODO add your handling code here:
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
try{
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse("D:\\test.xml");
Element root = doc.getDocumentElement();
NodeList nodelist1 = root.getElementsByTagName("FrameDefinitionSection");
String[] st= new String[4];
for(int i=0;i<nodelist1.getLength();i++)
{
Node node=nodelist1.item(i);
st[0]= node.getChildNodes().item(1).getTextContent();
st[1]= node.getChildNodes().item(3).getTextContent();
st[2]= node.getChildNodes().item(5).getTextContent();
st[3]= node.getChildNodes().item(7).getTextContent();
((DefaultTableModel) jTable1.getModel()).addRow(st);
}
}
catch(Exception ex)
{
System.out.print("error");
}
}
这是我的xml文件: 该表应该将此xml中的节点显示到表的字段中,但它不起作用! :
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<FrameDefinitionSection>
<FrameNameAndElements>
<FrameName>here is the frame's name</FrameName>
<FrameElements>its element</FrameElements>
</FrameNameAndElements>
<FrameDefinition>
<Definition>the definition of the frame</Definition>
</FrameDefinition>
<FrameExampleSentences>
<ExampleSentences>its example as well</ExampleSentences>
</FrameExampleSentences>
</FrameDefinitionSection>
答案 0 :(得分:1)
你最好使用它:
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse("D:\\test.xml");
Element root = doc.getDocumentElement();
NodeList nodelist1 =
root.getChildNodes();
String[] st = new String[4];
for (int i = 0; i < nodelist1.getLength(); i++)
{
Node node = nodelist1.item(i);
if (node.getNodeType() == node.ENTITY_NODE) {
st[0] = node.getChildNodes().item(1).getTextContent();
st[1] = node.getChildNodes().item(3).getTextContent();
st[2] = node.getChildNodes().item(5).getTextContent();
st[3] = node.getChildNodes().item(7).getTextContent();
((DefaultTableModel) jTable1.getModel()).addRow(st);
}
}
答案 1 :(得分:0)
如果您编写如下内容,则nodelist1为null。
NodeList nodelist1 = root.getElementsByTagName("FrameDefinitionSection");
所以你需要像这样改变,
NodeList nodelist1 = doc.getElementsByTagName("FrameDefinitionSection");