German English
Data Processing

XML - Extract sensor data from XML

This example shows how to parse XML (eXtensible Markup Language) data which contains sensor data. The implementation demonstrates the power of the radio module Preon32. For parsing the XML description the library "qdparser" is used. This library was originally developed for mobile phones with Java ME, but can also be used on Preon32 without adjustment.
/*
 * Copyright (c) 2011., Virtenio GmbH
 * All rights reserved.
 */

package com.virtenio.webdemo;

import com.twicom.qdparser.Element;
import com.twicom.qdparser.TaggedElement;
import com.twicom.qdparser.XMLParseException;
import com.twicom.qdparser.XMLReader;

import java.io.IOException;
import java.util.List;
import java.util.Map;

public class XmlParse {

    public static void main(String[] args) {
        String XmlStr =
                "<varisenA>\n" +
                "  <humidity Tr='30332' RHr='16196'/>\n" +
                "  <pressure Pr='341' Tr='453'/>\n" +
                "  <light raw='4041'/>\n" +
                "  <temp Tr='4400'/>\n" +
                "</varisenA>";
        try {
            parseXmlDescription(XmlStr);
        } catch (XMLParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void parseXmlDescription(String xmlStr) 
        throws XMLParseException, IOException {
        XMLReader parser = new XMLReader(xmlStr);
        try {
            parser.startDocument();
            TaggedElement tag = parser.parse();
            String name = tag.getName();
            if (name.equals("varisenA")) {
                List<Element> elements = tag.getElements();
                for (Element element : elements) {
                    tag = (TaggedElement) element;
                    Map<String, String> attributes = tag.getAttributes();
                    name = ((TaggedElement) element).getName();
                    if (name.equals("humidity")) {
                        int humidityRHr = Integer.parseInt(attributes.get("RHr"));
                        int humidityTr = Integer.parseInt(attributes.get("Tr"));
                    } else if (name.equals("pressure")) {
                        int pressureTr = Integer.parseInt(attributes.get("Tr"));
                        int pressurePr = Integer.parseInt(attributes.get("Pr"));
                    } else if (name.equals("light")) {
                        int lightRaw = Integer.parseInt(attributes.get("raw"));
                    } else if (name.equals("temp")) {
                        int tempTr = Integer.parseInt(attributes.get("Tr"));
                    }
                }
            }
            parser.endDocument();
        } catch (XMLParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}