I m new to Android (porting iOS/Objective C app ) and I have to read an XML (with some nodes in JSON) file returned by a WebService
the response looks like that:
<SOAP-ENV:Envelope><SOAP-ENV:Body><ns1:TPLoginResponse><TPLoginResult>[{"content": "some json content...."]</TPLoginResult></ns1:TPLoginResponse></SOAP-ENV:Body></SOAP-ENV:Envelope>
how can I simply get the content of TPLoginResult ?
I tried :
httpTransport.call(SOAP_ACTION, envelope);
Object response = envelope.getResponse();
SoapObject SoapResponse = (SoapObject)envelope.bodyIn;
Log.e("Info", "response : " + SoapResponse.toString() ); // content is successfully received here
String SResponse = SoapResponse.toString();
Log.e("Info", "DocumentBuilderFactory" );
// parse the XML as a W3C Document
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
builderFactory.setNamespaceAware(true);
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document document = builder.parse( new InputSource(new StringReader(SResponse)) );
NodeList nList = document.getElementsByTagName("TPLoginResult");
Log.e("info","nList length : " + nList.getLength());
but I need a 0 length nList ...
I also tryed :
NodeList nList = document.getElementsByTagName("ns1:TPLoginResponse");
but same 0 length result..
Any suggestions ?
I think the key is in this line:
builderFactory.setNamespaceAware(true);
if you comment that line you'd be able to get the element with
document.getElementsByTagName("TPLoginResponse");
otherwise, you'll probably need to use:
document.getElementsByTagNameNS(namespaceURI,tag);
but i have never used the last line, so i can't help you there.
please let me know how that works for you, i'm interested.
KSOAP Android is a very useful tool to consume SOAP web-services. I use this tool in all my Android applications. And I can say that it works well.
You can find examples in their wiki and all over internet.
Finally I found that it is more easy usign the ksoap methods
String LoginResponse = SoapResponse.getProperty(0).toString();
Related
I am new to android programming.My requirement is to invoke the web services.I successfully got the response from web services.how to parse the response in android.Give me solution.
This is the code for getting response:
HttpResponse response = httpclient.execute(httppost);
String str=response.getStatusLine().toString();
System.out.println("========URL STATUS========"+str);
HttpEntity r_entity = response.getEntity();
if( r_entity != null ) {
result = new byte[(int) r_entity.getContentLength()];
if(r_entity.isStreaming()) {
is = new DataInputStream(r_entity.getContent());
is.readFully(result);
}
}
httpclient.getConnectionManager().shutdown();
String responsedata= (new String(result).toString());
The below sample is for dom parser.
DocumentBuilderFactory dbf =DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
StringReader sr=new StringReader(result.toString());
is.setCharacterStream(sr);
Document doc = db.parse(is);
NodeList nodes = doc.getElementsByTagName("your root tag");
//get your other tag elements.
http://www.mkyong.com/java/how-to-read-xml-file-in-java-dom-parser/. Example of dom parser.
http://www.mkyong.com/java/how-to-read-xml-file-in-java-sax-parser/. Example of sax parser.
Dom is w3c based parser. Dom is slower than sax cause it uses tree node and has to be in mmeory. So parsing large data using DOM parser is not recommended.
SAX on the other hand is faster than dom. Recommended for large xml data.
The above links gives you examples of both. Use any of the above parser to parse and get values from the xml tags.
You can try to use SimpleXmlParser. It's a native android class. It's simpler than DOM xml parser.
what you need is simply a android xml parse library. There are plenty of xml parse for android.
official tutorial
there is also a article "comparing methods for xml parsing in android"
I'm using google map route for my own android application. 2 days ago it worked well, but after that when the application runs its giving me errors via logcat. Can any body tell me a reason and solution for this problem.
org.xml.sax.SAXParseException: unterminated entity ref (position:ENTITY_REF :799 in java.io.InputStreamReader#406cdeb0)
private String[] getDirectionData(String sourceLat, String sourceLong, String destinationLat, String destinationLong) {
String urlString = "http://maps.google.com/maps?f=d&hl=en&" +"saddr="+sourceLat+","+sourceLong+"&daddr="+destinationLat+","+destinationLong + "&ie=UTF8&0&om=0&output=kml";
Log.d("URL", urlString);
Document doc = null;
HttpURLConnection urlConnection = null;
URL url = null;
String pathConent = "";
try {
url = new URL(urlString.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.connect();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
doc = db.parse(urlConnection.getInputStream());
} catch (Exception e) {
Log.w("Error in google map",e);
}
NodeList nl = doc.getElementsByTagName("LineString");
for (int s = 0; s < nl.getLength(); s++) {
Node rootNode = nl.item(s);
NodeList configItems = rootNode.getChildNodes();
for (int x = 0; x < configItems.getLength(); x++) {
Node lineStringNode = configItems.item(x);
NodeList path = lineStringNode.getChildNodes();
pathConent = path.item(0).getNodeValue();
}
}
String[] tempContent = pathConent.split(" ");
return tempContent;
}
In my case this problem appeared on a .png file inside /res/drawable folder. It is a bug, and it was reported here. So, for future reference, if you are facing it on a drawable, check that out. To summarize, update your ADT to, at least, the version 21.0.1.
I have encountered the same problem. After debugging, I found that it was caused by the '&' character. it should be escaped
I dont know sure but I think is because output=kml is not longer available a lot of users are having troubles with it.
The error message is pretty suggestive: The ref tag is unterminated, e.g. the <ref> doesn't have an enclosing </ref> pair. Validate your XML input with a tool like this.
I was myself facing the same problem. This exception is coming because some important KML elements have been deprecated by google recently. For example, refer GeometryCollection .
If your code tries to find any such elements in the received document, it might throw
an SAXParseException: unterminated entity ref .
They have introduced a new API for Maps. It is available here .
I myself downloaded the kml file, and stored it in the device. When I had a look at it
using the editor, I did not find the element my code was looking for. However, if you use the kml file to find a route in the latest Chrome Version, it works.
I got the same problem. It was in a .png image file. The problem occurred after I edited the file. I searched for the solution but after that I cleaned my project using "clean.." option under "project" tab. SO finally I got rid of that "
I am trying to fetch checkin locations from Google places API but I am getting error for XML FileNotFoundException when I try to read it through url.openStream(). My key is correct because I tried using it in some other URL in browser. If someone has used this feature then please let me know how to do this. Here is my code:
public String checkingMessage()
{
String strURL = "https://maps.googleapis.com/maps/api/place/check-in/xml?sensor=true&key=" + GOOGLE_API_KEY;
URL url;
try
{
url = new URL(strURL.replace(" ", "%20"));
// Standard of reading a XML file
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder;
Document doc = null;
XPathExpression expr = null;
builder = factory.newDocumentBuilder();
doc = builder.parse(new InputSource(url.openStream()));
// Create a XPathFactory
XPathFactory xFactory = XPathFactory.newInstance();
// Create a XPath object
XPath xpath = xFactory.newXPath();
// Compile the XPath expression
expr = xpath.compile("//reference/text()");
// Run the query and get a nodeset
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
String answer = nodes.item(0).getNodeValue();
Toast.makeText(getApplicationContext(), answer, Toast.LENGTH_LONG);
}catch(Exception ex){
ex.printStackTrace();
}
return null;
}
If I use direct url in browser, I get following error:
400: Your client has issued a malformed or illegal request. That’s all we know.
I dont know json parsing, so I am using XML. Output I believe should be like this, hence I am trying to fetch value of reference:
<CheckInRequest>
<reference>place_reference</reference>
</CheckInRequest>
Update : I tried using HttpResponse and get response into Entity as follows
if (httpResponse.getStatusLine().getStatusCode() == 200){
strResult = EntityUtils.toString(httpResponse.getEntity());
}
But then I get MalFormedException on
doc = builder.parse(strResult); // doc is Document type
Either ways how can I get xml result into doc
I think you are trying to fetch check-in locations. I would like to do the same. But the check-in API seems to be POST-only at the moment, at least that's how I read the API documentation. Meaning your application can check-in, but you cannot query who checked in where (not even you yourself).
i am new in android development, i don't know how to parse data from xml, so please help.
this is my Xml which i have to parse.
<MediaFeedRoot>
<MediaTitle>hiiii</MediaTitle>
<MediaDescription>hellooooo.</MediaDescription>
<FeedPath>how r u</FeedPath>
</MediaFeedRoot>
Thanx in advance.
I dont understand that why people ask the question here without searching properly on net.Please do remember that search on net before asking anything here....
Below is the link where you can find a very good tutorial about xml parsing...
http://www.androidpeople.com/android-xml-parsing-tutorial-%E2%80%93-using-domparser
My suggestion is starting from the basic step:
think about your xml file connection: url? local?
instance a DocumentBuilderFactory and a builder
DocumentBuilder dBuilder =
DocumentBuilderFactory.newInstance().newDocumentBuilder();
OR
URLConnection conn = new URL(url).openConnection();
InputStream
inputXml = conn.getInputStream();
DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
Document xmlDoc = docBuilder.parse(inputXml);
Parsing XML file:
Document xmlDom = dBuilder.parse(xmlFile);
After that, it turns a xml file into DOM or Tree structure, and you have to travel a node by node.
In your case, you need to get content. Here is an example:
String getContent(Document doc, String tagName){
String result = "";
NodeList nList = doc.getElementsByTagName(tagName);
if(nList.getLength()>0){
Element eElement = (Element)nList.item(0);
String ranking = eElement.getTextContent();
if(!"".equals(ranking)){
result = String.valueOf(ranking);
}
}
return result;
}
return of the getContent(xmlDom,"MediaTitle") is "hiiii".
Good luck!
Xml parsing api is throwing sax parse exception, If i try to parse a xml file which has attributes at root node.
One thing i have noticed is that, this happens if there is a UTF-8 BOM character at the start of the string, if i remove the BOM character things work fine. This code is working fine on 3.0 sdk and below, i saw this problem only in 3.1
am using following parser:
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = docFactory.newDocumentBuilder();
Document doc = null;
StringReader sr = new StringReader(xmlString);
InputSource is = new InputSource(sr);
doc = builder.parse(is);
Try this:
public Document parse(String xml) throws ParsingFailedException {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
//encode the xml to UTF -8
ByteArrayInputStream encXML = new ByteArrayInputStream(xml.getBytes("UTF8"));
Document doc = builder.parse(encXML);
log.error("XML parsing OK");
return doc;
} catch (Exception e) {
log.error("Parser Error:" + e.getMessage());
throw new ParsingFailedException("Failed to parse XML : Document not well formed", e);
}
}
Thanks evilone,
I have opened a issue with google, and they will be fixing this in their branch.
http://code.google.com/p/android/issues/detail?id=16892
Comments from google developer:
"I've prepared a fix for the root problem in our internal Honeycomb tree. But you don't need the fix for your code. Your parseXml method should just take an InputStream rather than a String. You can pass that directly to the InputSource constructor."