parsing does not working in android - android

I am parsing a xml from an url.The url is has mobile IMEI no and searchstring based on my application. i put my xml parsing code in android project it does not work. but if i run as separate java program it is working. please help me.
Log.e("rsport-", "function1");
try{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setIgnoringComments(true);
factory.setCoalescing(true); // Convert CDATA to Text nodes
factory.setNamespaceAware(false); // No namespaces: this is default
factory.setValidating(false); // Don't validate DTD: also default
DocumentBuilder parser = factory.newDocumentBuilder();
Log.e("rsport-", "function2");
Document document = parser.parse("http://demo.greatinnovus.com/restingspot/search?userid=xxxxxxxxxxxxxxxx&firstname=a&lastname=a");
Log.e("rsport-","function3");
NodeList sections = document.getElementsByTagName("Searchdata");
int numSections = sections.getLength();
for (int i = 0; i < numSections; i++)
{
Element section = (Element) sections.item(i);
if(section.hasChildNodes()==true){
NodeList section1=section.getChildNodes();
for(int j=0;j<section1.getLength();j++){
if(section1.item(j).hasChildNodes()==true) {
for(int k=0;k<section1.item(j).getChildNodes().getLength();k++)
xmlvalue=String.valueOf(section1.item(j).getChildNodes().item(k).getNodeValue()).trim();
arl.add(xmlvalue);
}
}
}
}
}
}
catch(Exception e){}
System.out.println("id"+id+" searchdatacount"+searchdatacount);
System.out.println("---------");
ListIterator<String> litr = arl.listIterator();
while (litr.hasNext()) {
String element = litr.next();
Log.e("rsport-", "elememt");
}
after the Log.e("rsport-", "function2"); does not work.

Refer my blog, i had gave Detailed explanation, http://sankarganesh-info-exchange.blogspot.com/2011/04/parsing-data-from-internet-and-creating.html, and make sure , that you had add the Internet permission in your Manifest file.
If you had gone through Myblog, then you will able to notice that you did the following line as wrong
Document document = parser.parse("http://demo.greatinnovus.com/restingspot/search?userid=xxxxxxxxxxxxxxxx&firstname=a&lastname=a");
use like this
URL url =new URL("http://demo.greatinnovus.com/restingspot/search?userid=xxxxxxxxxxxxxxxx&firstname=a&lastname=a");
Document document= parser.parse(new InputSource(url.openStream()));

Related

Xml parsing in Android with XPath

Perhaps I'm going about this the wrong way, I'm trying to parse a gpx file, I've never parsed xml format in android before, I've tried a few different ways and can't seem to get any results.
The xml is at the bottom (a snippet its really long!). I want the trkpt nodes, actually the only data I need it lat, lon and time.
The last method I tired was using Xpath. It always returns an empty node list.
try {
InputSource inputSrc = new InputSource(context.getResources().openRawResource(R.raw.sample_track));
XPath xpath = XPathFactory.newInstance().newXPath();
String expression = "//trkpt";
NodeList nodes = (NodeList)xpath.evaluate(expression, inputSrc, XPathConstants.NODESET);
also tried this:
private List<Location> decodeGPX(Context context) {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(context.getResources().openRawResource(R.raw.sample_track));
Element elementRoot = document.getDocumentElement();
NodeList nodelist_trk = elementRoot.getElementsByTagName("trk");
for (int j = 0; j < nodelist_trk.getLength(); j++) {
Node node = nodelist_trk.item(j);
if (node.getNodeName().equals("trkseg")) {
NodeList trkpntList = node.getChildNodes();
XML:
<?xml version="1.0" ?>
<gpx>
<name><![CDATA[WassonPeak]]></name>
<desc><![CDATA[Wasson Peak is a classic hike in Saguaro National Park West. The destination is the high point of the Tucson Mountains at 4687 feet, Wasson peak. This map is of the eastern approach, from the trailhead at the end of Camino del Cerro.]]></desc>
<author><![CDATA[Scott Morris]]></author>
<email><![CDATA[smorris#topofusion.com]]></email>
<url><![CDATA[http://www.topofusion.com]]></url>
<urlname><![CDATA[TopoFusion Home Page]]></urlname>
<keywords><![CDATA[Wasson Saguaro West]]></keywords>
<bounds maxlat="32.288840" minlon="-111.150076" minlat="32.265301" maxlon="-111.120627"/>
<wpt lat="32.273882" lon="-111.147150">
<name><![CDATA[Wasson Peak]]></name>
<cmt><![CDATA[]]></cmt>
</wpt>
<wpt lat="32.288552" lon="-111.120627">
<name><![CDATA[Camino Del Cerro Trailhead]]></name>
<cmt><![CDATA[]]></cmt>
</wpt>
<wpt lat="32.265516" lon="-111.143047">
<name><![CDATA[Saddle]]></name>
<cmt><![CDATA[]]></cmt>
</wpt>
<trk>
<url><![CDATA[http://www.topofusion.com]]></url>
<urlname><![CDATA[TopoFusion Home Page]]></urlname>
<trkseg>
<trkpt lat="32.288668" lon="-111.120915">
<ele>847.058838</ele>
<time>2002-11-20T23:05:06Z</time>
</trkpt>
<trkpt lat="32.288668" lon="-111.120915">
<ele>847.539551</ele>
<time>2002-11-20T23:05:07Z</time>
</trkpt>
<trkpt lat="32.288668" lon="-111.120915">
<ele>847.058838</ele>
<time>2002-11-20T23:05:08Z</time>
</trkpt>
Your first one method is one of the way you can get the job done!
String path = "StringPath.xml";
InputStream is = new FileInputStream(new File(ruta));
InputSource inputSrc = new InputSource(is);
XPath xpath = XPathFactory.newInstance().newXPath();
String expression = "//trkpt";
NodeList nodes = (NodeList)xpath.evaluate(expression, inputSrc, XPathConstants.NODESET);
for (int i=0; i < nodes.getLength(); i++){
NamedNodeMap node = nodes.item(i).getAttributes();
System.out.println(node.toString());
}
When I try the code with the xml above, I get 3 item on terminal

Encoding issue on Kit Kat / Android when saving and reading a webview

I have noticed that for Android 4.4 handsets, saving a webview with:
webview.saveWebArchive(name);
and reading it after with WebArchiveReader WebArchiveReader (see code below) throws an Encoding Exception:
11-08 15:10:31.976: W/System.err(2240): org.xml.sax.SAXParseException: Unexpected end of document
11-08 15:10:31.976: W/System.err(2240): at org.apache.harmony.xml.parsers.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:125)
The method used to read the stored XML file worked perfectly fine until 4.3 and it is (NOTE: I tried to parse it in two different ways):
public boolean readWebArchive(InputStream is) {
DocumentBuilderFactory builderFactory =
DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
myDoc = null;
try {
builder = builderFactory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
try {
//New attempt
InputSource input = new InputSource(is);
input.setEncoding("UTF-8");
myDoc = builder.parse(input);
//This used to be the way it used to work for
//Android 4.3 and below without trouble
//myDoc = builder.parse(is);
NodeList nl = myDoc.getElementsByTagName("url");
for (int i = 0; i < nl.getLength(); i++) {
Node nd = nl.item(i);
if(nd instanceof Element) {
Element el = (Element) nd;
// siblings of el (url) are: mimeType, textEncoding, frameName, data
NodeList nodes = el.getChildNodes();
for (int j = 0; j < nodes.getLength(); j++) {
Node node = nodes.item(j);
if (node instanceof Text) {
String dt = ((Text)node).getData();
byte[] b = Base64.decode(dt, Base64.DEFAULT);
dt = new String(b);
urlList.add(dt);
urlNodes.add((Element) el.getParentNode());
}
}
}
}
} catch (SAXParseException se){
//Some problems parsing the saved XML file
se.printStackTrace();
myDoc = null;
} catch (Exception e) {
e.printStackTrace();
myDoc = null;
}
return myDoc != null;
}
I've played a bit with the way the buider is invoked. Instead of giving it a FileInputStream, I first create an InputSource as you can see to force a given encoding. However, I had no success. By not including the InputSource, the exception was instead:
org.xml.SAXParseException: Unexpected token
I've read in previous posts that this may be an encoding issue (e.g. android-utf-8-file-parsing) but none of the proposed solutions worked for me.
Does anyone else have the same issue or does anyone know what has changed on Kit Kat, and if so, how could it be avoided?
Many thanks in advance
My WebArchiveReader code is not needed under Android 4.4 KitKat and newer to read back a saved web archive. If you save your page with webview.saveWebArchive(name); method on KitKat, you get an MHTML formatted file, as "#Dragon warrior" indicates above. To read this file back into webview, just use:
webView.loadUrl("file:///my_folder/mySavedPage.mht");
Just make sure to give your file the .mht or .mhtml extension, so that WebView recognizes its contents. Otherwise it may just display the MHTML code in text format.
Greg
I have the exactly same problem as you do.
Apparently, Android 4.4 WebView saves web archives as MHTML. Therefore, you can't use WebArchiveReader anymore.
You might want to parse MHTML files with some other 3rd party lib. Good luck!

How to get sub elements of an xml in android?

InputStream is = openHTTPConnection("blahblah");
DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
Document doc = null;
try {
builder = fac.newDocumentBuilder();
doc = builder.parse(is);
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
doc.getDocumentElement().normalize();
NodeList parentNodes = doc.getElementsByTagName("Parent");
for (int i = 0; i < parentNodes.getLength(); i++){
Node itemNode = parentNodes.item(i);
if (itemNode.getNodeType() == Node.ELEMENT_NODE){
Element parentElement = (Element) itemNode;
NodeList childNodes = ??????
}
}
My XML file:
<Blah>
<Parent>
<Child>
...
</Child>
</Parent>
</Blah>
How can I get the sub element of Parent? The tutorial says NodeList childNodes = (parentElement).getElementsByTagName("Child"); But it does not make sense to me.
It looks like my post is mostly code; But I don't know what to add
Tutorial is correct. This is how you get it:
NodeList childNodes = (parentElement).getElementsByTagName("Child");
Element childElement=(Element)childNodes.item[0];
In case , there are multiple <child> nodes, you can loop through the iterator
In this way you can get sub elements of an xml in android
You could write a xsl
<xsl:template match="/">
<xsl:for-each select="section">
<xsl:value-of select="concat('link ',photo#id, ' from ',#name,' is ',photo#ilink)"><xsl:value-of>
</xsl:for-each>
</xsl:template>
run the xsl on your xml, the output will be link 1 from section1 is ImageLink 1 .. link 4 from section2 is ImageLink 2

How to modify XML node value?

I am new developer in java application. I would like to modify an XML file node value. I have used an xml file for modify as follows
<staff id="2">
<firstname>yong</firstname>
<lastname>mook kim</lastname>
<nickname>mkyong</nickname>
<salary>2000000</salary>
<age>28</age>
</staff>
in above xml I would like to change salary value as 345375. For this modification I have written code as follows
try{
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(new File("/sdcard/myxml.xml"));
//Get the staff element by tag name directly
Node nodes = doc.getElementsByTagName("staff").item(0);
//loop the staff child node
NodeList list = nodes.getChildNodes();
for (int i =0; i<list.getLength();i++){
Node node = list.item(i);
//get the salary element, and update the value
if("salary".equals(node.getNodeName())){
node.setNodeValue("345375");
}
}
}
catch (Exception e) {
e.printStackTrace();
}
if I use this way that value not modifying salary.
How can I modify an XML node value?
First you have to realize that node.setValue() is modifying the representation that is stored in memory. Knowing that, then you just need to figure out how to write that output to disk. See this, for an example.
node.Text = "Enter your value here"; //This will work

Using DOM parser in Android

I'm using the DOM parser to retrive information from a XML file that looks like this:
<data>
<metData>
<wantedInformation>
</metData>
<metData>
<Information>
</metData>
<metData>
<Information>
</metData>
<data>
The problem is because I don't know how to parse only the first part of <metData>. I don't need the second and the third part, but the parser displays them anyway.
The xml file is from a weather forcast site:
http://www.meteo.si/uploads/probase/www/fproduct/text/sl/fcast_SLOVENIA_MIDDLE_latest.xml
and I need just the following line: <nn_shortText>oblačno</nn_shortText>
Pls take care whether your XML file is well formed or not,
You have to the notice three methods which i had shown below, they are
1. getElementsByTagName - Mention the tag which you want to parse
2.getChildNodes - retervies the child node
3.getNodeValue()- with the help of this method you can access the
value of particular tag
Step 1: Create a Method to parse _Information_Value ,inorder to parse the data of Information tag
String[] infoId=null;
public void parse_Information_Value() throws UnknownHostException{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
Document dom = builder.parse(this.getInputStream());
org.w3c.dom.Element root = dom.getDocumentElement();
NodeList items = root.getElementsByTagName("metData");
int a=items.getLength();
int k=0;
for (int i = 0; i < items.getLength(); i++) {
Message_category message = new Message_category();
Node item = items.item(i);
NodeList properties = item.getChildNodes();
for (int j = 0; j < properties.getLength(); j++) {
Node property = properties.item(j);
String name = property.getNodeName();
if (name.equalsIgnoreCase("wantedInformation")) {
message.setId(property.getFirstChild()
.getNodeValue());
infoId[k]=property.getFirstChild().getNodeValue();
k++;
}
}
}
} catch (Exception e) { }
}
Depending on the size of your document, you may also want to use at a streaming oriented parser like SAX or Stax, which does not pull the whole document into memory and thus needs less memory than DOM.
Good thing is that SAX is already built into Android, so you can use it right away.
See this link for a usage example.

Categories

Resources