简体   繁体   English

尝试解析Java中的XML文件并将变量存储在ArrayList中

[英]Trying to parse an XML File in Java and store variables in an ArrayList

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: 我试图解析Java中的以下XML文件,并将XTimeStamp变量存储在ArrayList中,并将YVoltage存储在另一个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: 这是我目前必须完成的Java代码:

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: 当我运行代码时,我得到以下输出,从底部的ArrayLists列表可以看出,这是一个问题:

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. 谢谢。

Try this: 尝试这个:

Instead of: 代替:

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

Do (if you can add Strings to XTimeStamp ): 做(如果您可以将字符串添加到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. 请记住,Java中的约定是将变量的首字母小写。

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. 我不明白为什么在执行System.out.println时,为什么要在您的ArrayList XML元素(toString方法显示标记名称,以及一些关于所包含属性的信息(而不是内部文本)的标签中)?要求您花时间将XML元素转换为其有效内容。

My advice ? 我的建议 ? Take the string you use for your System.out.println and put it in your ArrayLists. 取得用于System.out.println的字符串,并将其放入ArrayLists。

I find it easier to use xpath for this type of xml data aggregation: 我发现将xpath用于这种类型的xml数据聚合比较容易:

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM