adamb53
adamb53

Reputation: 17

Parsing XML returns incorrect number of children in Java

I am parsing a very simple XML file but the issue I am having is when I return the number of children.

My XML File:

<?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>

And my Java Code is this:

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;
        }
    }

What happens is the output says

"There are: 7 sensors."

While it should say

"There are: 3 sensors."

I have tried removing the white space as I have read in a lot of posts about white space but this did not change anything, I also tried removing the attribute for one of the sensors in the XML document but this also did not change anything.

I also tried using NodeList and then output the getLength() but that also did not return the correct number of sensors.

Any ideas?

Upvotes: 0

Views: 100

Answers (2)

Lital Kolog
Lital Kolog

Reputation: 1331

Have you tried:

NodeList entities = sensorDoc.getElementsByTagName("Sensor");
System.out.println("There are: " + entities.getLength()+ " sensors.");

what is the output?

Upvotes: 1

SPIRiT_1984
SPIRiT_1984

Reputation: 2787

The getNextSibling returns the node immediately following this node. That means the child node Path too. Therefore you have much more items.

Upvotes: 0

Related Questions