Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7923059
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 3, 20262026-06-03T17:10:46+00:00 2026-06-03T17:10:46+00:00

I am trying to pass an XML string from a server into a parser

  • 0

I am trying to pass an XML string from a server into a parser and make an array list of objects but all I am currently getting is an empty array list.

Code for fetching and parsing XML

package parkinglot_api;

import java.net.*;
import java.sql.Date; 
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.io.*;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

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

public class ParkingLotInstance {
/*
 * Parking Lot API instance
 *      Constructor
 *          URL - String
 *      getParkingLotInfo()
 *          Returns XML from Specified Server
 *      parseParkingLotInfo()
 *          XML - String
 *          Returns ArrayList of Lot Objects
 */

public static URL serverURL;

public ParkingLotInstance( URL connurl ){
    serverURL = connurl;
}

public String getParkingLotInfo(){
    //Get a response from API server

    URL APIurl = this.serverURL;
    String APIresponse = "";

    System.out.println(APIurl);
    try {
        APIurl.openConnection();
        BufferedReader in = new BufferedReader(
                new InputStreamReader(APIurl.openStream()));

        String output;
        while ((output = in.readLine()) != null)
            APIresponse += output;
        in.close();

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return APIresponse;

}

public ArrayList parseParkingLotInfo( String XML ){
        ArrayList lots = new ArrayList();

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

        try {

            //Using factory get an instance of document builder

             dbf.setNamespaceAware(false);
             DocumentBuilder builder = dbf.newDocumentBuilder();

             InputSource inStream = new InputSource();

             inStream.setCharacterStream(new StringReader(XML));
             Document dom = builder.parse(inStream);


            //get the root element
            Element docEle = dom.getDocumentElement();

            //get a nodelist of elements
            NodeList nl = docEle.getElementsByTagName("Lot");

            if(nl != null && nl.getLength() > 0) {
                for(int i = 0 ; i < nl.getLength();i++) {

                    //get the employee element
                    Element el = (Element)nl.item(i);

                    //get the Employee object
                    Lot l = parseLot(el);

                    //add it to list
                    lots.add(l);
                }
            }


        }catch(ParserConfigurationException pce) {
            pce.printStackTrace();
        }catch(SAXException se) {
            se.printStackTrace();
        }catch(IOException ioe) {
            ioe.printStackTrace();
        }


        return lots;
}

public Lot parseLot(Element el){

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd");

    //Initialize Parking Lot Variables
    int id = getIntValue(el,"id");
    int occupancy = getIntValue(el,"occupancy");
    Boolean status = Boolean.parseBoolean(getTextValue(el,"status"));
    String name = getTextValue(el,"name");
    Date updated = null;
    try {
        updated = (Date) dateFormat.parse(getTextValue(el,"updated"));
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } 
    String description = getTextValue(el,"description");

    //Construct Parking Lot
    Lot lot = new Lot( 
         id
       , occupancy 
       , status
       , name
       , updated
       , description 
      );

    return lot;
}

/**
 * I take a xml element and the tag name, look for the tag and get
 * the text content
 * i.e for <employee><name>John</name></employee> xml snippet if
 * the Element points to employee node and tagName is 'name' I will return John
 */
private String getTextValue(Element ele, String tagName) {
    String textVal = null;
    NodeList nl = ele.getElementsByTagName(tagName);
    if(nl != null && nl.getLength() > 0) {
        Element el = (Element)nl.item(0);
        textVal = el.getFirstChild().getNodeValue();
    }

    return textVal;
}


/**
 * Calls getTextValue and returns a int value
 */
private int getIntValue(Element ele, String tagName) {
    //in production application you would catch the exception
    return Integer.parseInt(getTextValue(ele,tagName));
}
}

The Object Class

 package parkinglot_api;

 import java.util.Date;
 import com.google.gson.Gson;
 import com.google.gson.GsonBuilder;
 import com.thoughtworks.xstream.XStream;
 import com.thoughtworks.xstream.io.xml.DomDriver;

 public class Lot {
/*
 * Parking Lot Object
 *     ID: Unique Identifier
 *     Occupancy: The Current Amount of Cars in the Lot
 *     Status: Describes if the Lot is Open or Closed
 *     Name: A String Identifier of the Lot
 *     Updated: The Last time the Lot's current status record was updated.
 */

//Initiate Parking Lot Fields
public int id;
public int occupancy;
public Boolean status;
public String description;
public String name;
public Date updated;

//Parking Lot Constructor
public Lot( 
      int newId
    , int newOccupancy 
    , Boolean newStatus
    , String newName
    , Date newUpdated
    , String newDescription 
){

    id = newId;
    occupancy = newOccupancy;
    status = newStatus;
    name = newName;
    updated = newUpdated;
    description = newDescription;
}

//Convert Java Object to JSON
public String toJSON(){
    Gson gson = new GsonBuilder().setPrettyPrinting().create();

    String jsonLot = gson.toJson(this);
    return jsonLot;
}

//Convert Java Object to XML
public String toXML(){
    XStream xstream = new XStream(new DomDriver());
    xstream.alias("lot", Lot.class);
    String xml = xstream.toXML(this);

    return xml;
}
}

The Class that calls the methods from teh instance class

 package parkinglot_api;

 import java.net.MalformedURLException;
 import java.net.URL;
 import java.util.ArrayList;


 public class Example {

/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub
    URL serverURL;
    try {
        serverURL = new URL("http://localhost:8080");

        ParkingLotInstance API = new ParkingLotInstance(serverURL);

        String parkingLotXML = API.getParkingLotInfo();

        ArrayList Lots = API.parseParkingLotInfo(parkingLotXML);

        System.out.println(Lots);

    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

 }

The XML

<?xml version='1.0' ?>
    <campus count='4'>
    <lot>
      <id>1</id>
      <occupancy>25</occupancy>
      <status>true</status>
      <description></description>
      <name>lot1</name>
      <updated class="sql-date">2012-10-05</updated>
    </lot>
    <lot>
      <id>2</id>
      <occupancy>25</occupancy>
      <status>true</status>
      <description></description>
      <name>lot2</name>
      <updated class="sql-date">2012-10-06</updated>
    </lot>
    <lot>
      <id>3</id>
      <occupancy>25</occupancy>
      <status>false</status>
      <description></description>
      <name>lot3</name>
      <updated class="sql-date">2012-10-07</updated>
    </lot>
    <lot>
      <id>4</id>
      <occupancy>25</occupancy>
      <status>true</status>
      <description></description>
      <name>lot4</name>
      <updated class="sql-date">2012-11-07</updated>
    </lot>
    </campus>
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-03T17:10:49+00:00Added an answer on June 3, 2026 at 5:10 pm

    getElementsByTagName("...") is case-sensitive, you have "lot" in your file and docEle.getElementsByTagName("Lot") in your code, try to replace it with docEle.getElementsByTagName("lot")

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am trying to pass an XML list to a view but I am
I am trying to convert an XML string into and array. SimpleXmlIterator only accepts
I'm trying to create an XML string and pass it to another method where
I'm trying to pass elements from a list to a for loop and of
Iam trying to pass dynamic argument values i.e username from request using spring ioc.But
I'm trying to pass a build number from Hudson into a Flex application. I've
I am trying to figure how to pass string value(url) from html form to
I'm trying to send an xml message to a server from a client app
I'm trying to pass arbitrary exceptions from a XMLRPC server to a client (both
So I know how to parse some XML structures but I am currently trying

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.