Search code examples
java-mekxml2

kxml2 Parsing Simple XML


I'm trying to parse a simple XML file in my j2me application. But the parsing fails:

XML File

<companies> 
       <company CompanyId="6"> 
           <CompanyName>Test Company 1</CompanyName> 
           <SapNumber>0</SapNumber> 
           <RootCompanyId>1</RootCompanyId> 
           <ParentCompanyId /> </company> 
    </companies>

Parser Snippet

    KXmlParser parser = new KXmlParser();
    parser.setInput(new InputStreamReader(new ByteArrayInputStream(input.getBytes())));
    parser.nextTag();
    parser.require(XmlPullParser.START_TAG, null, "companies");

    while(parser.nextTag() == XmlPullParser.START_TAG) 
    {
        Company temp_company = new Company();
        parser.require(XmlPullParser.START_TAG, null, "company");
        String CompanyID = parser.getAttributeValue(0);
        temp_company.putValue("CompanyId", CompanyID);
        while(parser.nextTag() == XmlPullParser.START_TAG) 
        {
            if(parser.getName() == "CompanyName")
            {
                temp_company.putValue("CompanyName", parser.nextText());
            }
        }
        parser.require(XmlPullParser.END_TAG, null, "company");
        listCompany.put(CompanyID, temp_company);
    }
    parser.require(XmlPullParser.END_TAG, null, "elements");

Solution

  • I guess I can see what is going wrong here. After you have matched the <company> tag and obtained the value of the CompanyId attribute, you enter a while loop. But observe what will happen at this point:

    1. The first time you execute the while condition, the parser will match the <CompanyName> start tag, thus the if condition will be true and you will obtain the text inside the tag.
    2. I am not too intimate with the inner workings of kXml but on the second iteration your parser state must be either pointing at the text node (that is inside the <CompanyName> tag) or at the end tag (ie. </CompanyName>). Either way, you while condition will fail because you are not at a start tag.
    3. At this point you require that the next tag be the end tag of <company>, however, your state has still not changed and this will not be satisfied.

    My best guess is that the internal pointer is pointing at the text node inside <CompanyName> and that is why you get the "unexpected type (position: Text: Test Company1..." message.