Home > Articles > Networking > Wireless/High Speed/Optical

  • Print
  • + Share This
Like this article? We recommend

Like this article? We recommend

How to Read the XML News File

Listing 1 is a brief and very high-level description of the XML file that the service uses. We have left out all the attributes because the meaning of the example is only to clarify the structure of the file. In the XML file, there is an RDF element, which holds one CHANNEL element and several ITEM elements. The CHANNEL element contains a brief description about the service and a link to a more detailed description.

Listing 1 )Overall Structure of the XML File

<?xml version="1.0" encoding="UTF-8" ?> 
<rdf>
 <channel>
 </channel>
 <item>
 </item>
 <item>
 </item>
</rdf:RDF>

Each of the ITEM elements contains a title, a description of the news, and some links to topics related to the news. We're interested in the title, which is inside the TITLE element. So we go through to XML file, take out all the titles, and put them in a string vector (or similar).

We use a special version of NanoXML that is made for MIDP. It's called kXMLElement, and it is free. The parsing of the document is relatively simple and it uses recursion. Listing 2 shows how it is done.

Listing 2 Parsing the XML Document

private void traverse(XmlParser parser) throws IOException {
   boolean leave = false;
   do {
     ParseEvent event = parser.read ();

     switch (event.getType ()) {
     case Xml.START_TAG:
       if (event.getName().equals("title")) inside=true;
       traverse (parser);
       break;

     case Xml.END_TAG:
       leave = true;
       inside = false;
       break;

     case Xml.END_DOCUMENT:
       leave = true;
       break;

     case Xml.TEXT:
       if (inside) {
        v.addElement(event.getText());
       }

       break;

     case Xml.WHITESPACE:
       break;

     default:
     }
   }
   while (!leave);
}

The parser goes through the document element by element. If it encounters a start tag, it uses recursion to go through that element. Every time the start tag is called "Title", the text part of the element is set to a vector. The menu is then constructed from this vector of strings.

  • + Share This
  • 🔖 Save To Your Account