tags:

views:

42

answers:

3

I am trying to parse the following XML file in Java and to store the XTimeStamp variable in an ArrayList and YVoltage in another ArrayList:

<?xml version = "1.0"?>
<Data>
<reading>
    <XTimeStamp> 12:00:00:01</XTimeStamp>
    <YVoltage>  0.6</YVoltage>
</reading>



<reading>
    <XTimeStamp> 12:00:00:02</XTimeStamp>
    <YVoltage>  0.5</YVoltage>
</reading>



<reading>
    <XTimeStamp> 12:00:00:025</XTimeStamp>
    <YVoltage>  0.5</YVoltage>
</reading>



<reading>
    <XTimeStamp> 12:00:00:031</XTimeStamp>
    <YVoltage>  0.1</YVoltage>
</reading>



<reading>
    <XTimeStamp> 12:00:00:039</XTimeStamp>
    <YVoltage>  -0.1</YVoltage>
</reading>



<reading>
    <XTimeStamp> 12:00:00:050</XTimeStamp>
    <YVoltage>  -0.2</YVoltage>
</reading>


<reading>
    <XTimeStamp> 12:00:01:01</XTimeStamp>
    <YVoltage>  0.01</YVoltage>
</reading>
</Data>

Here is the Java code I currently have to accomplish the task:

import java.util.*;
import java.io.File;
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 XMLReader {

    public static void main(String argv[]) {
        ArrayList XTimeStamp = new ArrayList();
        ArrayList YVoltage = new ArrayList();

        try {
            File file = new File("C:\\Users\\user\\My Documents\\MyXMLFile.xml");
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(file);
            doc.getDocumentElement().normalize();
            System.out.println("Root element "
                    + doc.getDocumentElement().getNodeName());
            NodeList nodeLst = doc.getElementsByTagName("reading");
            System.out.println("Data");

            for (int s = 0; s < nodeLst.getLength(); s++) {

                Node fstNode = nodeLst.item(s);

                if (fstNode.getNodeType() == Node.ELEMENT_NODE) {

                    Element fstElmnt = (Element) fstNode;
                    NodeList fstNmElmntLst = fstElmnt
                            .getElementsByTagName("XTimeStamp");
                    Element fstNmElmnt = (Element) fstNmElmntLst.item(0);
                    NodeList fstNm = fstNmElmnt.getChildNodes();
                    Element TimeStamp = (Element) fstNmElmntLst.item(0);
                    XTimeStamp.add(TimeStamp);
                    System.out.println("XTimeStamp : "
                            + ((Node) fstNm.item(0)).getNodeValue());
                    NodeList lstNmElmntLst = fstElmnt
                            .getElementsByTagName("YVoltage");
                    Element lstNmElmnt = (Element) lstNmElmntLst.item(0);
                    NodeList lstNm = lstNmElmnt.getChildNodes();
                    Element YValue = (Element) lstNm;
                    YVoltage.add(YValue);
                    System.out.println("YVoltage : "
                            + ((Node) lstNm.item(0)).getNodeValue());
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(XTimeStamp);
        System.out.println(YVoltage);
    }
}

When I run the code I am getting the following output, as can be seen from the listings of the ArrayLists at the bottom there is a problem:

Root element Data
Data
XTimeStamp :  12:00:00:01
YVoltage :   0.6
XTimeStamp :  12:00:00:02
YVoltage :   0.5
XTimeStamp :  12:00:00:025
YVoltage :   0.5
XTimeStamp :  12:00:00:031
YVoltage :   0.1
XTimeStamp :  12:00:00:039
YVoltage :   -0.1
XTimeStamp :  12:00:00:050
YVoltage :   -0.2
XTimeStamp :  12:00:01:01
YVoltage :   0.01
[[XTimeStamp: null], [XTimeStamp: null], [XTimeStamp: null], [XTimeStamp: null], [XTimeStamp: null],  [XTimeStamp: null], [XTimeStamp: null]]
[[YVoltage: null], [YVoltage: null], [YVoltage: null], [YVoltage: null], [YVoltage: null], [YVoltage: null], [YVoltage: null]]

Any help with this would be much appreciated.

Thanks.

+1  A: 

I don't understand why you put in your ArrayList XML elements (which toString method display the tag name and, from what I remember, some info about contained attributes, but not inner text), while when you do your System.out.println calls you take the time to transform you XML element into its valid content.

My advice ? Take the string you use for your System.out.println and put it in your ArrayLists.

Riduidel
+2  A: 

Try this:

Instead of:

Element TimeStamp = (Element) fstNmElmntLst.item(0);
XTimeStamp.add(TimeStamp);

Do (if you can add Strings to XTimeStamp):

String timeStamp = fstNm.item(0)).getNodeValue(); 
XTimeStamp.add(timeStamp);

Or do this if you want to save Elements (I'd recommend you to save the Strings)

Element timeStamp = (Element) fstNm.item(0)); 
XTimeStamp.add(timeStamp);

Remember that the convention in Java is to name the variables with the first letter lowercase.

pakore
Thanks for this suggestion. It worked :-)
Anthony Keane
+1  A: 

I find it easier to use xpath for this type of xml data aggregation:

package net.davymeers;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collection;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class XpathTest {
    private static String XMLSTRING = "<data>" + "<reading>\r\n"
            + "    <XTimeStamp> 12:00:00:02</XTimeStamp>\r\n"
            + "    <YVoltage>  0.5</YVoltage>\r\n" + "</reading>\r\n" + "\r\n"
            + "\r\n" + "\r\n" + "<reading>\r\n"
            + "    <XTimeStamp> 12:00:00:025</XTimeStamp>\r\n"
            + "    <YVoltage>  0.5</YVoltage>\r\n" + "</reading>\r\n" + "\r\n"
            + "\r\n" + "\r\n" + "<reading>\r\n"
            + "    <XTimeStamp> 12:00:00:031</XTimeStamp>\r\n"
            + "    <YVoltage>  0.1</YVoltage>\r\n" + "</reading>\r\n" + "\r\n"
            + "\r\n" + "\r\n" + "<reading>\r\n"
            + "    <XTimeStamp> 12:00:00:039</XTimeStamp>\r\n"
            + "    <YVoltage>  -0.1</YVoltage>\r\n" + "</reading>\r\n" + "\r\n"
            + "\r\n" + "\r\n" + "<reading>\r\n"
            + "    <XTimeStamp> 12:00:00:050</XTimeStamp>\r\n"
            + "    <YVoltage>  -0.2</YVoltage>\r\n" + "</reading>\r\n"
            + "</data>";

    /**
     * @param args
     */
    public static void main(final String[] args) {

        final Document doc = createDocument();
        final XPath xpath = createXpath();

        final NodeList xTimeStampNodes = findElements("//XTimeStamp/text()",
                doc, xpath);
        final Collection<String> xTimeStamps = convertToCollection(xTimeStampNodes);

        final NodeList yVoltageNodes = findElements("//YVoltage/text()", doc,
                xpath);
        final Collection<String> yVoltages = convertToCollection(yVoltageNodes);

        for (final String xTimeStamp : xTimeStamps) {
            System.out.println("xTimeStamp: " + xTimeStamp);
        }
        for (final String yVoltage : yVoltages) {
            System.out.println("yVoltage: " + yVoltage);
        }
    }

    private static Document createDocument() {
        Document doc = null;
        try {
            final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
                    .newInstance();
            documentBuilderFactory.setNamespaceAware(true); // never forget
                                                            // this!
            final DocumentBuilder builder = documentBuilderFactory
                    .newDocumentBuilder();
            doc = builder.parse(new ByteArrayInputStream(XMLSTRING
                    .getBytes("ISO-8859-1")));
        } catch (final UnsupportedEncodingException exception) {
            // TODO handle exception
        } catch (final SAXException exception) {
            // TODO handle exception
        } catch (final IOException exception) {
            // TODO handle exception
        } catch (final ParserConfigurationException exception) {
            // TODO handle exception
        }
        return doc;
    }

    private static XPath createXpath() {
        final XPathFactory xpathFactory = XPathFactory.newInstance();
        final XPath xpath = xpathFactory.newXPath();
        return xpath;
    }

    private static NodeList findElements(final String xpathExpression,
            final Document doc, final XPath xpath) {
        NodeList nodes = null;
        if (doc != null) {
            try {
                final XPathExpression expr = xpath.compile(xpathExpression);
                final Object result = expr
                        .evaluate(doc, XPathConstants.NODESET);
                nodes = (NodeList) result;
            } catch (final XPathExpressionException exception) {
                // TODO handle exception
            }
        }
        return nodes;
    }

    private static Collection<String> convertToCollection(final NodeList nodes) {
        final Collection<String> result = new ArrayList<String>();
        if (nodes != null) {
            for (int i = 0; i < nodes.getLength(); i++) {
                result.add(nodes.item(i).getNodeValue());
            }
        }
        return result;
    }

}
davyM