我正在解析一个非常简单的 XML 文件,但我遇到的问题是当我返回子级的数量时。
我的 XML 文件:
<?xml version="1.1" encoding="ISO-8859-1"?>
<Sensors>
<Sensor ID="1">
<Path>C:\Test\s1</Path>
</Sensor>
<Sensor ID="2">
<Path>C:\Test\s2</Path>
</Sensor>
<Sensor ID="3">
<Path>C:\Test\s3</Path>
</Sensor>
</Sensors>
我的 Java 代码是这样的:
private void checkSensors()
{
String name = "C:\\Test\\sensors.xml";
File fileName = new File(name);
if (!fileName.exists())
{
System.out.println("File doesn't Exists!!!!!");
}
else
{
System.out.println("File Exists, moving on..");
sensorDoc = getDocument(name);
int count = 0;
Element root = sensorDoc.getDocumentElement();
Node sensor = root.getFirstChild();
while (sensor != null)
{
count++;
sensor = sensor.getNextSibling();
}
System.out.println("There are: " + count + " sensors.");
}
}
private static Document getDocument(String name)
{
try
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setIgnoringComments(true);
factory.setIgnoringElementContentWhitespace(true);
factory.setValidating(true);
DocumentBuilder builder = factory.newDocumentBuilder();
builder.setErrorHandler(null);
System.out.println("Parsing...");
return builder.parse(new InputSource(name));
}
catch (Exception e)
{
return null;
}
}
输出显示发生了什么
"There are: 7 sensors."
虽然应该说
"There are: 3 sensors."
我尝试删除空格,因为我读过很多有关空格的帖子,但这并没有改变任何内容,我还尝试删除 XML 文档中其中一个传感器的属性,但这也没有改变任何东西。
我还尝试使用 NodeList,然后输出 getLength()
但也没有返回正确的传感器数量。
有什么想法吗?
最佳答案
你尝试过吗:
NodeList entities = sensorDoc.getElementsByTagName("Sensor");
System.out.println("There are: " + entities.getLength()+ " sensors.");
输出是什么?
关于java - 在 Java 中解析 XML 返回错误的子级数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20345700/