import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Vector;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Form;
import javax.microedition.midlet.*;
import org.kxml.Xml;
import org.kxml.kdom.Document;
import org.kxml.kdom.Element;
import org.kxml.parser.XmlParser;
/**
* @author bliss
*/
public class xmlparse extends MIDlet {
public static final String resfile_name = "test.xml";
Vector v=new Vector();
StringBuffer s=null;
public void startApp() {
beginParse();
Display display=Display.getDisplay(this);
Form f=new Form("ddddd");
f.append(v.firstElement().toString());
display.setCurrent(f);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void beginParse()
{
try
{
XmlParser parser = null;
Document doc = new Document();
try
{ //This is used for getting the file from same folder in which the code is present.
InputStream in = this.getClass().getResourceAsStream(resfile_name);
InputStreamReader isr = new InputStreamReader(in);
parser = new XmlParser( isr );
doc.parse( parser );
parser = null;
}
catch (IOException ioe)
{
parser = null;
doc = null;
return;
}
Element root = doc.getRootElement();
int child_count = root.getChildCount();
for (int i = 0; i < child_count ; i++ )
{
if (root.getType(i) != Xml.ELEMENT)
{
continue;
}
s=new StringBuffer();
Element kid = root.getElement(i);
if(root.getElement(i).toString()!=null)
{}
if(kid.getName().equals("User")) //Get Attributes from Name
{
s.append(kid.getAttribute(0).getValue());
v.addElement(kid.getAttribute(0).getValue());
}
if (!kid.getName().equals("User"))
{
continue;
}
int address_item_count = kid.getChildCount();
for (int j = 0; j < address_item_count ; j++)
{
if (kid.getType(j) != Xml.ELEMENT)
{
continue;
}
Element item = kid.getElement(j);
if(item.getName().equals("Work")) // Different Tags
{
s.append(":"+item.getText());
}
if(item.getName().equals("City"))
{
s.append("-"+item.getText());
}
if(item.getName().equals("Amount"))
{
if(item.getText()!=null)
{
s.append("-"+item.getText());
}
}
item = null;
}
System.out.println(s.toString()); //Just Print the Data at your Output Window
s=null;
kid = null;
}
}
catch(Exception e){}
}
}
/*
<?xml version="1.0" encoding="utf-8"?>
<UserData>
<User Name="ABC">
<Work>Job</Work>
<City>fsfjk</City>
<Amount>200</Amount>
</User>
<User Name="XYZ">
<Work>Labour</Work>
<City>sdfdsf</City>
<Amount>1000</Amount>
</User>
</UserData>
*/
steps:
1.download the kxml package
2.open netbeans after create the mobile project(j2me)
3. Right click in your project on project tree after select properties
4.select the Build->Libraries & Resources
5.clck Add jar/zip button after select your kxml package
6.use this code run successfully.
No comments:
Post a Comment