reading XML File from URL in Android - java

I experimented with several ways of opening an XML file from the link, but all the roads did not do any good.
In order to make sure that parsing XML File is good, I downloaded the file and put it in Asset folder to make parsing all of this good.
We can deduce from this the error in reading from url
URL is http://feeds.bbci.co.uk/sport/0/football/rss.xml?edition=uk
HttpClient httpclient = new DefaultHttpClient();
HttpGet httppost = new HttpGet(url.toString());
HttpResponse response = httpclient.execute(httppost);
InputStream in=response.getEntity().getContent();
OR
HttpURLConnection con=(HttpURLConnection)url.openConnection();
InputStream in=con.getInputStream();
OR
InputStream in =url.openStream();
please help me
My Problem solved thanx to all for your help.I should use AsyncTask class when i get File from Url

public void xmlReader() {
try {
URL url = new URL("http://feeds.bbci.co.uk/sport/0/football/rss.xml");
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory
.newDocumentBuilder();
Document document = documentBuilder.parse(new InputSource(url
.openStream()));
nodlist = document.getElementsByTagName("Youritem");
for (int i = 0; i < nodlist.getLength(); i++) {
Element element = (Element) nodlist.item(i);
NodeList nodlistid = element.getElementsByTagName("Id");
Element id = (Element) nodlistid.item(0);
NodeList nodlistBaslik = element.getElementsByTagName("tagname1");
Element baslik = (Element) nodlistBaslik.item(0);
NodeList nodlistDetay = element.getElementsByTagName("tagname2");
Element detay = (Element) nodlistDetay.item(0);
NodeList nodlistKaynak = element.getElementsByTagName("tagname3");
Element lat = (Element) nodlistKaynak.item(0);
NodeList nodelistMedia = element.getElementsByTagName("tagname4");
Element longi = (Element) nodelistMedia.item(0);
NodeList nodelistTur = element.getElementsByTagName("tagname5");
Element tur = (Element) nodelistTur.item(0);
// String resimURL =
// resim.getAttributes().getNamedItem("url").getNodeValue();
NodeList nodelistMedia1 = element.getElementsByTagName("enclosure");
Element picture= (Element) nodelistMedia1.item(0);
String pictureURL = resim.getAttributes().getNamedItem("picturetagname").getNodeValue();
xmltagname1.add(tagname1.getChildNodes().item(0).getNodeValue());
xmltagname2.add(tagname2.getChildNodes().item(0).getNodeValue());
xmltagname3.add(tagname3.getChildNodes().item(0).getNodeValue());
xmltagname4.add(tagname4.getChildNodes().item(0).getNodeValue());
xmltagname5.add(tagname5.getChildNodes().item(0).getNodeValue());
}
} catch (Exception e) {
e.printStackTrace();
}
}
I think this method helps you.. Take it easy

String TextHolder = "", TextHolder2 = "";
public class GetNotePadFileFromServer extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
String userId = SharedPrefHelper.getPrefsHelper().getPref(SharedPrefHelper.PREF_USER_ID);
try {
URL url = new URL(baseUrl+"fileName.xml");
BufferedReader bufferReader = new BufferedReader(new InputStreamReader(url.openStream()));
while ((TextHolder2 = bufferReader.readLine()) != null) {
TextHolder += TextHolder2;
}
bufferReader.close();
} catch (MalformedURLException malformedURLException) {
malformedURLException.printStackTrace();
TextHolder = malformedURLException.toString();
} catch (IOException iOException) {
iOException.printStackTrace();
TextHolder = iOException.toString();
}
return null;
}
#Override
protected void onPostExecute(Void finalTextHolder) {
Document doc = convertStringToXMLDocument( TextHolder );
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName(ApiConstant.ApiKeys.SMS_MESSAGE);
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
Sms sms = new Sms(
eElement.getElementsByTagName(ApiConstant.ApiKeys.SMS_IDS).item(0).getTextContent(),
eElement.getElementsByTagName(ApiConstant.ApiKeys.SMS_ADDRESS).item(0).getTextContent(),
eElement.getElementsByTagName(ApiConstant.ApiKeys.SMS_BODY).item(0).getTextContent(),
eElement.getElementsByTagName(ApiConstant.ApiKeys.SMS_READ).item(0).getTextContent(),
eElement.getElementsByTagName(ApiConstant.ApiKeys.SMS_DATE).item(0).getTextContent(),
eElement.getElementsByTagName(ApiConstant.ApiKeys.SMS_TYPE).item(0).getTextContent(),
false
);
LogClass.e("mysms",""+sms.getAddress());
smsArrayList.add(sms);
}
}
setUi();
progressDialog.dismiss();
super.onPostExecute(finalTextHolder);
}
}
new GetNotePadFileFromServer().execute();

Related

How to correctly get the values I want from Web REST GET from android app written in Java?

This is my API request:
http://api.met.no/weatherapi/locationforecast/1.9/?lat=59.91;lon=10.76
I need to get 2 values from the above, namely the TEMPERATURE's "value" below location and time and I need SYMBOL's "number" below location and time. But for now I only try to get the temperature value.
I have followed different guides, but nothing is helping.
This what I have right now. Inside MainActivity I have:
private class TemperatureTask extends AsyncTask<String, Void, Void> {
TextView tv;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(String... Url) {
try {
URL url = new URL(Url[0]);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
nodelist = doc.getElementsByTagName("time");
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
Node node = nodelist.item(0);
if(node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
testView.setText(testView.getText() + "\nTemperature: "
+ getNode("location", element));
}
}
}
private static String getNode(String tag, Element element) {
NodeList nodeList = element.getElementsByTagName(tag).item(0)
.getChildNodes();
Node value = (Node) nodeList.item(0);
return value.getNodeValue();
}
And then I called it with:
String apiUrl = "http://api.met.no/weatherapi/locationforecast/1.9/?lat=59.91;lon=10.76";
new TemperatureTask().execute(apiUrl);
Anyways, I dont get any Exceptions but
+ getNode("location", element));
returns nothing.
What can I do to get the temperature? The reason this takes a lot of time for me is that most XML I see dont have this format with attributes with many values like this.

Android xml get node value null

i have a xml
<DatosClientes>
<User>Prueba</User>
<intUserNumber>1487</intUserNumber>
<IdUser>1328</IdUser>
</DatosClientes>
How to read data in android ? when run all time return null in node value
public static void Parse(String response){
try{
DocumentBuilderFactory dbf = DocumentBuilderFactory
.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(response));
Document doc = db.parse(is);
doc.getDocumentElement().normalize();
NodeList datos = doc.getElementsByTagName("DatosClientes");
XmlParse parser = new XmlParse();
for (int i = 0; i < datos.getLength(); i++) {
Node node = datos.item(i);
Element fstElmnt = (Element) node;
NodeList nameList = fstElmnt.getElementsByTagName("User");
Log.e("log",String.valueOf(nameList.item(0).getNodeValue()));
}
}catch (Exception e){
e.printStackTrace();
}
}
my objetive is finally read value and convert into ArrayList
It sounds like you are trying to get a list of the values in the XML? That is, you want:
{ "Prueba", "1487", "1328" }
For that, you can do something like:
public static final String XML_CONTENT =
"<DatosClientes>"
+ "<User>Prueba</User>"
+ "<intUserNumber>1487</intUserNumber>"
+ "<IdUser>1328</IdUser>"
+ "</DatosClientes>";
public static final Element getRootNode(final String xml) {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(xml)));
return document.getDocumentElement();
} catch (ParserConfigurationException | SAXException | IOException exception) {
System.err.println(exception.getMessage());
return null;
}
}
public static final List<String> getValuesFromXml(final String xmlContent) {
Element root = getRootNode(xmlContent);
NodeList nodes = root.getElementsByTagName("*");
List<String> values = new ArrayList<>();
for (int index = 0; index < nodes.getLength(); index++) {
final String nodeValue = nodes.item(index).getTextContent();
values.add(nodeValue);
System.out.println(nodeValue);
}
return values;
}
public static void main (String[] args) {
final List<String> nodeValues = getValuesFromXml(XML_CONTENT);
}

Parsing the XML file has got error

Does anyone help find the problem why no xml file is not parsing with the following code.... the xml format can be seen here.
I tried to test line by line using log.i("your string goes here", xml); function but unable to see the execution of code when loop starts....
I have used to Splash activity in which AsyncTask() function is executed in the background and then ListActivity is used to display all the DOMParser activity output....
So anyone help me get out from this problem at all....
Thank you in advance
package com.wfwf.everestnewsapp.parser;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.jsoup.Jsoup;
import org.jsoup.select.Elements;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import android.widget.Toast;
public class DOMParser {
private RSSFeed _feed = new RSSFeed();
public RSSFeed parseXml(String xml) {
URL url = null;
try {
url = new URL(xml);
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
try {
// Create required instances
DocumentBuilderFactory dbf;
dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
// Parse the xml
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
// Get all <item> tags.
NodeList nl = doc.getElementsByTagName("item");
int length = nl.getLength();
for (int i = 0; i < length; i++) {
Node currentNode = nl.item(i);
RSSItem _item = new RSSItem();
NodeList nchild = currentNode.getChildNodes();
int clength = nchild.getLength();
// Get the required elements from each Item
// Ishwor changed the code j=0 and j= j+1
for (int j = 0; j < clength; j = j + 1) {
Node thisNode = nchild.item(j);
String theString = null;
/*//ishwor changed as
if (thisNode != null && thisNode.getFirstChild() != null) {
theString = thisNode.getFirstChild().getNodeValue();
}
*/
String nodeName = thisNode.getNodeName();
//theString = nchild.item(j).getFirstChild().getNodeValue();
if(nchild.item(j).getFirstChild().getNodeValue()!=null){
//if (theString != null) {
//String nodeName = thisNode.getNodeName();
if ("title".equals(nodeName)) {
// Node name is equals to 'title' so set the Node
// value to the Title in the RSSItem.
_item.setTitle(theString);
}
else if ("description".equals(nodeName)) {
_item.setDescription(theString);
// Parse the html description to get the image url
String html = theString;
org.jsoup.nodes.Document docHtml = Jsoup.parse(html);
Elements imgEle = docHtml.select("img");
_item.setImage(imgEle.attr("src"));
}
else if ("pubDate".equals(nodeName)) {
// We replace the plus and zero's in the date with
// empty string
String formatedDate = theString.replace(" +0000",
"");
_item.setDate(formatedDate);
}
}
}
// add item to the list
_feed.addItem(_item);
}
} catch (Exception e) {
}
// Return the final feed once all the Items are added to the RSSFeed
// Object(_feed).
return _feed;
}
}
private Document getDocument(InputStream stream) {
Document doc = null;
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
if (stream != null) {
doc = dBuilder.parse(stream);
doc.getDocumentElement().normalize();
} else {
}
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}
return doc;
}
private String getTagValue(String sTag, Element eElement) {
String value = "";
try {
NodeList nlList = eElement.getElementsByTagName(sTag).item(0)
.getChildNodes();
for (int i = 0; i < nlList.getLength(); i++) {
Node nValue = nlList.item(i);
if (nValue != null) {
value = value + nValue.getNodeValue().trim();
}
}
} catch (Exception e) {
}
return value;
}
public EntityBean parseDoLogin(String requestOutput) {
EntityBean response = null;
InputStream stream = (InputStream) new ByteArrayInputStream(
requestOutput.getBytes());
Document doc = getDocument(stream);
NodeList nodeList = doc.getElementsByTagName("startTag");
for (int i = 0; i < nodeList.getLength(); i++) {
Node nNode = nodeList.item(i);
Element iElement = (Element) nNode;
response = new EntityBean();
String result = new String(getTagValue("result", iElement));
response.setResult(result);
String msg = new String(getTagValue("message", iElement));
response.setMsg(msg);
}
return response;
}

How do I add an AsyncTask to this?

I am creating a Android app and I am fairly new to threading in general I have two different methods that I use to call two different webservices as shown below, so how do I change these to use the AsyncTask to run on a background thread?
My Code:
public List<String> getEvacRouteNames(){
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
BufferedReader in = null;
String page;
try {
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost();
request.setURI(URI)
//Add The parameters. The asmx webservice requires a double but gets posted as a string in a text field
List<NameValuePair> nameValPairs = new ArrayList<NameValuePair>(0);
request.setEntity(new UrlEncodedFormEntity(nameValPairs));
HttpResponse response = client.execute(request);
in = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
page = sb.toString();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(new StringReader(page)));
// normalize the document
doc.getDocumentElement().normalize();
// get the root node
NodeList nodeList = doc.getElementsByTagName("string");
// the node has three child nodes
for (int n = 0; n < nodeList.getLength(); n++) {
Node node=nodeList.item(n);
String upperNode = node.getNodeName();
Node temp=node.getChildNodes().item(n);
if (upperNode.equals("string")){
String routeName = node.getTextContent();
routeNamesList.add(node.getTextContent());
}
}
//System.out.println(page);
} catch (Exception E) {
E.printStackTrace();
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return routeNamesList;
}
public EvacRoute getEvacuationRoute(String routeName, LatLng currentLocation, String lat, String lon) throws URISyntaxException, ClientProtocolException, IOException, ParserConfigurationException, SAXException{
evacRouteList = new ArrayList<EvacRoute>();
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
EvacRoute evacRoute = new EvacRoute();
evacRoute.setDestinationName(routeName);
BufferedReader in = null;
String page;
latslngsList = new ArrayList<LatLng>();
try {
latslngsList.add(currentLocation);
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost();
request.setURI(URI)
//Add The parameters. The asmx webservice requires a double but gets posted as a string in a text field
List<NameValuePair> nameValPairs = new ArrayList<NameValuePair>(2);
nameValPairs.add(new BasicNameValuePair("Route_Name", routeName));
nameValPairs.add(new BasicNameValuePair("In_Lat", lat));
nameValPairs.add(new BasicNameValuePair("In_Lon", lon));
request.setEntity(new UrlEncodedFormEntity(nameValPairs));
HttpResponse response = client.execute(request);
in = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
page = sb.toString();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(new StringReader(page)));
// normalize the document
doc.getDocumentElement().normalize();
// get the root node
NodeList nodeList = doc.getElementsByTagName("simple_ll_waypoint");
double latitude = 0;
double longitude= 0;
// the node has three child nodes
for (int n = 0; n < nodeList.getLength(); n++) {
String latString = "";
String longString = "";
Node node=nodeList.item(n);
String upperNode = node.getNodeName();
StringBuilder addressStrBlder = new StringBuilder();
for (int i = 0; i < node.getChildNodes().getLength(); i++) {
Node temp=node.getChildNodes().item(i);
String nodeName = temp.getNodeName();
String nodevalue = temp.getNodeValue();
if(temp.getNodeName().equalsIgnoreCase("Lat")){
latString = temp.getTextContent();
latitude = Double.parseDouble(latString);
} else if(temp.getNodeName().equalsIgnoreCase("Lon")){
longString = temp.getTextContent();
longitude = Double.parseDouble(longString);
LatLng latlng = new LatLng(latitude, longitude);
latslngsList.add(latlng);
}
}
//Log.e("Fuel Stop", fuelStop.toString());
}
//System.out.println(page);
} catch (Exception E) {
E.printStackTrace();
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
evacRoute.setLatLngList(latslngsList);
evacRouteList.add(evacRoute);
return evacRoute;
}
You can extend your class from AsyncTask and do like this:
public class AsyncCustomTask extends AsyncTask<Void, Void, List<String>> {
#Override
protected List<String> doInBackground(Void... params) {
return getEvacRouteNames();
}
#Override
protected void onPostExecute(List<String> result) {
// Function finished and value has returned.
}
}
And to call it:
new AsyncCustomTask().execute();
Updated for second question
For the method that have parameters, you can use constructor of your class like:
public class AsyncSecondCustomTask extends AsyncTask<Void, Void, EvacRoute> {
private final String routeName;
private final LatLng currentLocation;
private final String lat;
private final String lon;
public AsyncSecondCustomTask(String routeName, LatLng currentLocation, String lat, String lon) {
this.routeName = routeName;
this.currentLocation = currentLocation;
this.lat = lat;
this.lon = lon;
}
#Override
protected EvacRoute doInBackground(Void... params) {
return getEvacuationRoute(routeName, currentLocation, lat, lon);
}
#Override
protected void onPostExecute(EvacRoute result) {
// Function finished and value has returned.
}
}
And you can call it like:
new AsyncSecondCustomTask("", null, "", "").execute();

XPath with namespace in Java

I would like to get all the content in between the tags but I do not know how to do this because of the urn: namespace.
<urn:ResponseStatus version="1.0" xmlns:urn="urn:camera-org">
<urn:requestURL>/CAMERA/Streaming/status</urn:requestURL>
<urn:statusCode>4</urn:statusCode>
<urn:statusString>Invalid Operation</urn:statusString>
<urn:id>0</urn:id>
</urn:ResponseStatus>
Any ideas?
Short answer: use XPath local-name(). Like this: xPathFactory.newXPath().compile("//*[local-name()='requestURL']/text()"); will return /CAMERA/Streaming/status
Or you can implement a NamespaceContext that maps namespaces names and URIs and set it on the XPath object before querying.
Take a look at this blog article, Update: the article is down, you can see it on webarchive
Solution 1 sample:
XPath xpath = XPathFactory.newInstance().newXPath();
String responseStatus = xpath.evaluate("//*[local-name()='ResponseStatus']/text()", document);
System.out.println("-> " + responseStatus);
Solution 2 sample:
// load the Document
Document document = ...;
NamespaceContext ctx = new NamespaceContext() {
public String getNamespaceURI(String prefix) {
return prefix.equals("urn") ? "urn:camera-org" : null;
}
public Iterator getPrefixes(String val) {
return null;
}
public String getPrefix(String uri) {
return null;
}
};
XPath xpath = XPathFactory.newInstance().newXPath();
xpath.setNamespaceContext(ctx);
String responseStatus = xpath.evaluate("//urn:ResponseStatus/text()", document);
System.out.println("-> " + responseStatus);
Edit
This is a complete example, it correctly retrieve the element:
String xml = "<urn:ResponseStatus version=\"1.0\" xmlns:urn=\"urn:camera-org\">\r\n" + //
"\r\n" + //
"<urn:requestURL>/CAMERA/Streaming/status</urn:requestURL>\r\n" + //
"<urn:statusCode>4</urn:statusCode>\r\n" + //
"<urn:statusString>Invalid Operation</urn:statusString>\r\n" + //
"<urn:id>0</urn:id>\r\n" + //
"\r\n" + //
"</urn:ResponseStatus>";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new java.io.ByteArrayInputStream(xml.getBytes()));
XPath xpath = XPathFactory.newInstance().newXPath();
xpath.setNamespaceContext(new NamespaceContext() {
public String getNamespaceURI(String prefix) {
return prefix.equals("urn") ? "urn:camera-org" : null;
}
public Iterator<?> getPrefixes(String val) {
return null;
}
public String getPrefix(String uri) {
return null;
}
});
XPathExpression expr = xpath.compile("//urn:ResponseStatus");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
Node currentItem = nodes.item(i);
System.out.println("found node -> " + currentItem.getLocalName() + " (namespace: " + currentItem.getNamespaceURI() + ")");
}
XML xpath with Namespace
Simple XML
String namespaceXML = "<?xml version='1.0' ?><information><person id='1'><name>Deep</name><age>34</age><gender>Male</gender></person> <person id='2'><name>Kumar</name><age>24</age><gender>Male</gender></person> <person id='3'><name>Deepali</name><age>19</age><gender>Female</gender></person><!-- more persons... --></information>";
String jsonString = "{}";
String expression = "//information";
Name space XML
String namespaceXML = "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body><m:NumberToDollarsResponse xmlns:m=\"http://www.dataaccess.com/webservicesserver/\"><m:NumberToDollarsResult>nine hundred and ninety nine dollars</m:NumberToDollarsResult></m:NumberToDollarsResponse></soap:Body></soap:Envelope>";
String jsonString = "{'soap':'http://schemas.xmlsoap.org/soap/envelope/', 'm':'http://www.dataaccess.com/webservicesserver/'}";
String expression = "//m:NumberToDollarsResponse/m:NumberToDollarsResult/text()";
Supply namespace xml file as a string, to asscerionXpath(namespaceXML, jsonString, expression) method and get result in the form of text/node.
text() : nine hundred and ninety nine dollars
node :
<m:NumberToDollarsResult xmlns:m="http://www.dataaccess.com/webservicesserver/">
nine hundred and ninety nine dollars
</m:NumberToDollarsResult>
public static String asscerionXpath(String namespaceXML, String jsonString, String expression){
if(namespaceXML.indexOf("><") > -1) namespaceXML = namespaceXML.replace("><", ">\r\n<");
if(jsonString.indexOf("'") > -1) jsonString = jsonString.replace("'", "\"");
System.out.println("namespaceXML : \n"+namespaceXML);
System.out.println("nsmespaces : \n"+jsonString);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);
factory.setNamespaceAware(true);
factory.setIgnoringComments(true);
factory.setIgnoringElementContentWhitespace(true);
try {
DocumentBuilder builder = factory.newDocumentBuilder();
Document source = builder.parse( string2Source(namespaceXML) );
XPath xpath = XPathFactory.newInstance().newXPath();
addNameSpaces(jsonString, xpath);
// An XPath expression is not thread-safe. Make sure it is accessible by only one Thread.
XPathExpression expr = xpath.compile(expression);
// The NodeList interface provides the abstraction of an ordered collection of nodes,
NodeList nodes = (org.w3c.dom.NodeList) expr.evaluate(source, XPathConstants.NODESET);;
Node tree_base = nodes.item(0);
return document2String(tree_base);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (XPathExpressionException e) {
System.out.println("If the expression cannot be evaluated.");
}
return "";
}
static InputSource string2Source( String str ) {
InputSource inputSource = new InputSource( new StringReader( str ) );
return inputSource;
}
static void addNameSpaces(String jsonString, XPath xpath) {
JSONParser parser = new JSONParser();
try {
JSONObject namespaces = (JSONObject) parser.parse(jsonString);
if (namespaces.size() > 0) {
final JSONObject declaredPrefix = namespaces; // To access in Inner-class.
NamespaceContext nameSpace = new NamespaceContext() {
// To get all prefixes bound to a Namespace URI in the current scope, XPath 1.0 specification
// --> "no prefix means no namespace"
public String getNamespaceURI(String prefix) {
Iterator<?> key = declaredPrefix.keySet().iterator();
System.out.println("Keys : "+key.toString());
while (key.hasNext()) {
String name = key.next().toString();
if (prefix.equals(name)) {
System.out.println(declaredPrefix.get(name));
return declaredPrefix.get(name).toString();
}
}
return "";
}
public Iterator<?> getPrefixes(String val) {
return null;
}
public String getPrefix(String uri) {
return null;
}
};// Inner class.
xpath.setNamespaceContext( nameSpace );
}
} catch ( org.json.simple.parser.ParseException e) {
e.printStackTrace();
}
}

Categories