我有一个下表的简单 XML 表示形式。当我只遍历顶层时,使用代码(包含在下面)。我得到 5 个节点,而实际上提供的示例中只有 2 个(theader 和 tbody)。有人可以解释为什么吗?
package testparser;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Vector;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class TestParser {
private static final int FILE_small = 1;
private static final int FILE_medium = 2;
private static final int FILE_large = 3;
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
doDomTest(1);
}
private static void doDomTest(int sizeId) {
String filename = getFileNameFromId(sizeId);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
FileInputStream fis = new FileInputStream(filename);
Document doc = db.parse(fis);
Element topElement = doc.getDocumentElement();
NodeList nl = topElement.getChildNodes();
int ilen = nl.getLength();
print("Top Element count " + ilen);
for (int i=0;i<ilen;i++){
Node node = nl.item(i);
if (node.getNodeType()==Node.TEXT_NODE) {
print(i + ". Name:" + node.getNodeName() + "= " + node.getNodeValue() + ". type " + node.getNodeType());
} else {
print(i + ". Name:" + node.getNodeName() + ", type " + node.getNodeType());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static String getFileNameFromId(int sizeId) {
String sReturn = "";
switch (sizeId) {
case FILE_small:
sReturn = "D:/temp/testdata_ok.xml";
break;
case FILE_medium:
sReturn = "D:/temp/testdata_ok.xml";
break;
case FILE_large:
sReturn = "D:/temp/testdata_ok.xml";
break;
}
return sReturn;
}
private static void print(String sValue) {
System.out.println(sValue);
}
}
测试数据
<?xml version="1.0" encoding="utf-8"?>
<table>
<theader>
<tr>
<th>Title Col1</th>
<th>Title Col2</th>
<th>Title Col3</th>
<th>Title Col4</th>
</tr>
</theader>
<tbody>
<tr>
<td>data:R1C1</td>
<td>data:R1C2</td>
<td>data:R1C3</td>
<td>data:R1C4</td>
</tr>
<tr>
<td>data:R2C1</td>
<td>data:R2C2</td>
<td>data:R2C3</td>
<td>data:R2C4</td>
</tr>
<tr>
<td>data:R3C1</td>
<td>data:R3C2</td>
<td>data:R3C3</td>
<td>data:R3C4</td>
</tr>
<tr>
<td>data:R4C1</td>
<td>data:R4C2</td>
<td>data:R4C3</td>
<td>data:R4C4</td>
</tr>
<tr>
<td>data:R5C1</td>
<td>data:R5C2</td>
<td>data:R5C3</td>
<td>data:R5C4</td>
</tr>
</tbody>
</table>
控制台输出
Top Element count 5
0. Name:#text=
. type 3
1. Name:theader, type 1
2. Name:#text=
. type 3
3. Name:tbody, type 1
4. Name:#text=
. type 3
请注意输出中如何报告theader 和tbody(第1 行和第3 行),但我也有项目0、2 和4。为什么额外的节点?我本来希望只列出 0 和 1 的行,分别用于 theader 和 tbody 。
“type 1”/“type 3”表示“getNodeType()”方法的值,也打印在输出中。我在这里找到了 getNodeType() 的含义。
我正在使用 JDK 1.6.0u24