You Are Here:

Community: Wiki

This page was last modified 10:50, 5 June 2009.

How to parse an XML file in J2ME with kXML

From Forum Nokia Wiki

We'll see how to parse a generic XML file using kXML library.

Source code: XmlNode class

First, we'll define an XmlNode class to represent a generic XmlNode. We'll define 2 node types:

  • Text nodes: nodes without a name, containing only a textual value
  • Element nodes: nodes with a tag name, containing children nodes

Each node will have also a list of attributes.

public class XmlNode
{
	public static final int TEXT_NODE = 0;
	public static final int ELEMENT_NODE = 1;
	
	public int nodeType = 0;
	public String nodeName = null;
	public String nodeValue = null;
	public Vector children = null;
	public Hashtable attributes = null;
	
	public XmlNode(int nodeType)
	{
		this.nodeType = nodeType;
		this.children = new Vector();
		this.attributes = new Hashtable();
	}
	public String[] getAttributeNames()
	{
		String[] names = new String[attributes.size()];
		
		Enumeration e = attributes.keys();
		
		int i = 0;
		
		while(e.hasMoreElements())
		{
			names[i] = (String)e.nextElement();
			
			i++;
		}
		return names;
	}
	public void setAttribute(String key, String value)
	{
		attributes.put(key, value);
	}
	public String getAttribute(String key)
	{
		return (String)attributes.get(key);
	}
	
	public void addChild(XmlNode child)
	{
		this.children.addElement(child);
	}
}

Source code: GenericXmlParser class

GenericXmlParser is the class with which we'll able to parse XML files. It has only one public method, parseXML(), that will accept as arguments:

  • a KXmlParser instance to do parsing
  • a boolean that defines if whitespaces-only children must be ignored
import org.kxml2.io.KXmlParser;
import org.xmlpull.v1.XmlPullParser;
 
public class GenericXmlParser
{
	public XmlNode parseXML(KXmlParser parser, 
            boolean ignoreWhitespaces) throws Exception
	{
		parser.next();
		
		return _parse(parser, ignoreWhitespaces);
	}
	XmlNode _parse(KXmlParser parser, 
                  boolean ignoreWhitespaces) throws Exception
	{
		XmlNode node = new XmlNode(XmlNode.ELEMENT_NODE);
		
		if(parser.getEventType() != XmlPullParser.START_TAG)
		{
			throw new Exception("Illegal XML state: " + 
                                     parser.getName() + ", " + parser.getEventType());
		}
		else
		{
			node.nodeName = parser.getName();
			
			for(int i = 0; i < parser.getAttributeCount(); i++)
			{
				node.setAttribute(parser.getAttributeName(i),     parser.getAttributeValue(i));
			}
			
			parser.next();
			
			while(parser.getEventType() != XmlPullParser.END_TAG)
			{
				if(parser.getEventType() == XmlPullParser.START_TAG)
				{
					node.addChild(_parse(parser, ignoreWhitespaces));
				}
				else if(parser.getEventType() == XmlPullParser.TEXT)
				{
					if(!ignoreWhitespaces || !parser.isWhitespace())
					{
						XmlNode child = new XmlNode(XmlNode.TEXT_NODE);
						
						child.nodeValue = parser.getText();
						
						node.addChild(child);
					}
				}
				parser.next();
			}
		}
		return node;
	}
}

Source code: sample usage

To use the classes defined above, you can simply do as follows:

InputStreamReader reader = new InputStreamReader(getClass().getResourceAsStream("/test3.xml"));
			
KXmlParser parser = new KXmlParser();
			
parser.setInput(reader);
 
GenericXmlParser gParser = new GenericXmlParser();
			
XmlNode xml = gParser.parseXML(parser, true);

And, if you want to dump out the parsed XML data, you can use the following method:

void dumpXML(XmlNode node, int deep)
{
	for(int i = 0; i < deep; i++)
	{
		System.out.print(" ");
	}
	System.out.print(node.nodeName + " - ");
	
	if(node.nodeValue != null)
	{
		System.out.print("(" + node.nodeValue + ") - ");
	}
	String[] attributes = node.getAttributeNames();
	
	for(int i = 0; i < attributes.length; i++)
	{
		System.out.print(attributes[i] + ": " + node.getAttribute(attributes[i]) + ", ");
	}
		
	System.out.println();
		
	for(int i = 0; i < node.children.size(); i++)
	{
		dumpXML((XmlNode)node.children.elementAt(i), deep + 1);
	}
}

Rate This

 
Bookmark this page: DeliciousDiggFacebookGoogleYahooStumbleUponRedditFurlTechnocratiMagnoliaTwitter  Share this page Share this page Print this Page Print this page Invite a friend Invite a friend
Email Newsletters Press Terms & Conditions Privacy Policy Sitemap Contact Us © 2009 Nokia 
RDF Facets: qdcZdescriptionQSxEa0E20WikiE20javaE20symbianE5fosE20s60E20maemoE20cE2bE2bE20WikiE20HomeE20WikiE20HelpE20OverviewE20GlossaryE20CreateE20PageE20ProposeE20anE20ArticleE20SpotlightE20TopicE20E2dE20WE52TE20WidgetsE20ProgrammingE20E4canguageE20E2dE20SymbianE20CE2bE2bE20E2dE20OpenE20CE2fCE2bE2bE20E2dE20JavaE20E2dE20FlashE20E4citeE20E2dE20PythonE20WebE20TechnologiesE20E2dE20WE52TE20WidgetsE20E2dE20WidSetsE20ToolsE20andE20SE44KE20CodeE20E45E78amplesE20KnowledgeE20BaseE20TechnologyE20AreasE20SoftwareE20PlatformsE20E44evelopmentE20ProcessE20E3fE3fWikiE20ChineseE20E3fE3fE3fWikiE20JapaneseE20PortugueseE2fBrazilianE20E52ussianE20WhatE20linksE20hereE20UploadE20fileE20SpecialE20pagesE20PrintableE20versionE44ownloadE20asE20PE44FE20GoE20ToE20E2eE2eE2eX qdcZidentifierQSxhttpE3aE2fE2fwikiE2eforumE2enokiaE2ecomE2findeE78E2ephpE2fPublishingE5fyourE5fownE5fwidgetsX qdcZpublisherQUxhttpE3aE2fE2fswE2enokiaE2ecomE2fidE2fc764fd1cE2d8b06E2d499aE2d9a6aE2d17c3903d5a65E2fforumE5fnokiaE5fcrawlerE5fagentX qdcZtitleQSxPublishingE20yourE20ownE20widgetsE20E2dE20ForumE20NokiaE20WikiX qdcZtypeQUqfnZE45E78cludedFromGeneralE4cistingsQ qdcZtypeQUqfnTypeZCommunityContentQ qdcZtypeQUqfnTypeZE52esourceQ qdcZtypeQUqfnTypeZWebpageQ qdcZtypeQUqfnTypeZWikiContentQ qdcZtypeQUqmarsZManagedE52esourceQ qdcZtypeQUqwebZInformationE52esourceQ qdcZtypeQUqwebZPageQ qdcZtypeQUqwebZE52esourceQ qdcZtypeQUqrdfsZE52esourceQ qrssZdescriptionQSxEa0E20WikiE20javaE20symbianE5fosE20s60E20maemoE20cE2bE2bE20WikiE20HomeE20WikiE20HelpE20OverviewE20GlossaryE20CreateE20PageE20ProposeE20anE20ArticleE20SpotlightE20TopicE20E2dE20WE52TE20WidgetsE20ProgrammingE20E4canguageE20E2dE20SymbianE20CE2bE2bE20E2dE20OpenE20CE2fCE2bE2bE20E2dE20JavaE20E2dE20FlashE20E4citeE20E2dE20PythonE20WebE20TechnologiesE20E2dE20WE52TE20WidgetsE20E2dE20WidSetsE20ToolsE20andE20SE44KE20CodeE20E45E78amplesE20KnowledgeE20BaseE20TechnologyE20AreasE20SoftwareE20PlatformsE20E44evelopmentE20ProcessE20E3fE3fWikiE20ChineseE20E3fE3fE3fWikiE20JapaneseE20PortugueseE2fBrazilianE20E52ussianE20WhatE20linksE20hereE20UploadE20fileE20SpecialE20pagesE20PrintableE20versionE44ownloadE20asE20PE44FE20GoE20ToE20E2eE2eE2eX qfnZdistributionQUxhttpE3aE2fE2fwikiE2eforumE2enokiaE2ecomE2fX qfnZtypeQUqfnTypeZCommunityContentQ qfnZtypeQUqfnTypeZE52esourceQ qfnZtypeQUqfnTypeZWebpageQ qfnZtypeQUqfnTypeZWikiContentQ qfnZupdatedQDx2008E2d10E2d02X qmarsZdescriptionQSxEa0E20WikiE20javaE20symbianE5fosE20s60E20maemoE20cE2bE2bE20WikiE20HomeE20WikiE20HelpE20OverviewE20GlossaryE20CreateE20PageE20ProposeE20anE20ArticleE20SpotlightE20TopicE20E2dE20WE52TE20WidgetsE20ProgrammingE20E4canguageE20E2dE20SymbianE20CE2bE2bE20E2dE20OpenE20CE2fCE2bE2bE20E2dE20JavaE20E2dE20FlashE20E4citeE20E2dE20PythonE20WebE20TechnologiesE20E2dE20WE52TE20WidgetsE20E2dE20WidSetsE20ToolsE20andE20SE44KE20CodeE20E45E78amplesE20KnowledgeE20BaseE20TechnologyE20AreasE20SoftwareE20PlatformsE20E44evelopmentE20ProcessE20E3fE3fWikiE20ChineseE20E3fE3fE3fWikiE20JapaneseE20PortugueseE2fBrazilianE20E52ussianE20WhatE20linksE20hereE20UploadE20fileE20SpecialE20pagesE20PrintableE20versionE44ownloadE20asE20PE44FE20GoE20ToE20E2eE2eE2eX qmarsZlanguageQUxhttpE3aE2fE2fswE2enokiaE2ecomE2flanguageE2d1E2fenX qrdfZtypeQUqfnZE45E78cludedFromGeneralE4cistingsQ qrdfZtypeQUqfnTypeZCommunityContentQ qrdfZtypeQUqfnTypeZE52esourceQ qrdfZtypeQUqfnTypeZWebpageQ qrdfZtypeQUqfnTypeZWikiContentQ qrdfZtypeQUqmarsZManagedE52esourceQ qrdfZtypeQUqwebZInformationE52esourceQ qrdfZtypeQUqwebZPageQ qrdfZtypeQUqwebZE52esourceQ qrdfZtypeQUqrdfsZE52esourceQ
User Rating: qfnZuserE5FratingQNx3E2E0000X