I am trying to parse this XML onto my Android Application.
I read quite a few questions on parsing the XML here on stackoverflow, yet I am not sure how to handle a for loop everyone mentioned, in my case.
If someone would be nice enough to give me a working example for this case of XML, I'd be very grateful.
THE EXAMPLE CODE I FOUND ON STACKOVERFLOW
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(*/Insert my URL/*);
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName(*/What to write here in my case?/*);
item = new TextView[nodeList.getLength()];
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
item[i] = new TextView(this);
Element fstElmnt = (Element) node;
NodeList itemList = fstElmnt.getElementsByTagName(*/What to write here in my case?/*);
Element itemElement = (Element) itemList.item(0);
itemList = itemElement.getChildNodes();
item[i].setText("item = "
+ ((Node) itemList.item(0)).getNodeValue());
layout.addView(item[i]);
}
}
catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
/** Set the layout view to display */
setContentView(layout);
}
The above code is NOT an example that I am using. It's just what I found on the internet how to parse XML on Android App. But my XML seems more complex than the ussually posted ones here.
use XmlPullParser for parsing XML in your android application. It is very easy to use and pretty fast.
I use XmlPullParser in all my applications.
Follow this tutorial it has nice example on how to use XmlPullParser.
http://www.vogella.com/tutorials/AndroidXML/article.html
Related
I am trying to get all arrays I store in: https://s3.eu-west-2.amazonaws.com/tekstpieprz/strings.xml
I would like to use them for my textviews. I have added Unirest but cannot get my head around JSON. I have tried to play with something like:
HttpResponse<JsonNode> request = (HttpResponse<JsonNode>) Unirest.get("https://s3.eu-west-2.amazonaws.com/tekstpieprz/strings.xml")
.getBody("docukrz");
JSONObject myObj = request.getBody().getObject();
final JSONArray results = myObj.getJSONArray(String docukrz);
so then I can use the array in:
final String[] docukrz = res.getStringArray(R.array.docukrz);
But instead using
Resources
I would like to use the array I store online.
I do not fully understand how JSON works, I have only started learning JAVA 6 weeks ago. Any help would be much much appreciated.
You can find XML prase example here How can I parse xml from url in android?.
according to that answer, your code should be like below
URL url = new URL("https://s3.eu-west-2.amazonaws.com/tekstpieprz/strings.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("docukrz");
ArrayList resourceList = new ArrayList();
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
resourceList.add(node);
}
i have been traipsing the internet for days and i really need some help, i am trying to parse in an XML document from a web server into a ListView in android, i have worked out how to do it with a local file and that is fine, but no matter what i find whether on stack or other sites it just doesnt seem to work, can anyone help me with this?? i know the page exists and works...ive pulled all my hair out now so pleas help :)
below is my code for the method, this is called after the on create and an onclicklistener for items,also i am using the document builder factory method.
private void xmlparse()
{
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = dbf.newDocumentBuilder();
Document doc = builder.parse(new URL("URL in here").openConnection().getInputStream());
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("item");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
titles.add(getTagValue(TITLE_1, eElement)); //TITLE_1 is the xml tag title
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private String getTagValue(String sTag, Element eElement) {
NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();
Node nValue = (Node) nlList.item(0);
return nValue.getNodeValue();
}
Am i missing something daft or have i missed the ball completely? can anyone point me to infomation which would help or just let me know :)
Cheers!!
I've made which do that task, you should do this following :
//Formattage des strings pour le passage en URL
from = URLEncoder.encode(from, "UTF-8");
to = URLEncoder.encode(to, "UTF-8");
String addressToConnect = "http://maps.googleapis.com/maps/api/distancematrix/xml?origins="+from+"&destinations="+to+"&mode=driving&units="+unit+"&sensor=false";
//Partie connexion
URL url = new URL(addressToConnect);
HttpURLConnection connexion = (HttpURLConnection) url.openConnection();
connexion.connect();
InputSource geocoderResultInputSource;
geocoderResultInputSource = new InputSource(connexion.getInputStream());
//Partie XML/XPATH
Document geocoderResultDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(geocoderResultInputSource);
XPath xpath = XPathFactory.newInstance().newXPath();
//On s'assure que la requete envoy�e � l'API � bien renvoy�e un STATUS = OK cf. Google API
NodeList nodeListCodeResult = (NodeList) xpath.evaluate("//status", geocoderResultDocument, XPathConstants.NODESET);
etc...
Hope it helps,
I'm stumped, hopefully I've just done a dumb thing that I can fix easily.
I'm passing in a String full of XML, being 'XMLstring'. I want to get one of the elements and print the child nodes in a "name = value" on the console. The problem is that the console keeps printing garbage along with the element name that I cannot work out how to get rid of.
Anyway, this code:
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(XMLstring));
Document doc = db.parse(is);
NodeList nodes = doc.getElementsByTagName("client-details");
Node node = nodes.item(0);
NodeList client_details = node.getChildNodes();
for (int i = 0; i < client_details.getLength(); i++) {
System.out.println(client_details.item(i).getNodeName()+" = "+getTextContents(client_details.item(i)));
}
}
catch (Exception e) {
e.printStackTrace();
}
Gives me the following:
#text =
testing-mode = false
#text =
name = testman
#text =
age = 30
Why is it printing the "#text ="? How do I get rid of it?
I am using NetBeans if that helps.
You want to use getNodeValue() instead:
System.out.println(client_details.item(i).getNodeValue()+" = "+getTextContents(client_details.item(i)));
If you look in the table at the top of this page, you see that for Text nodes, getNodeName() returns #text.
I am curious to see what each of the two function calls in your System.out.println() is printing out separately, only because the entire output should be on one line. One of those two is causing the problems, and i believe it may be internal to the function.
Otherwise, if you use String splitString = string.split("[=]"); it will split up the line based on the delimeter '='
then you can
String splitString = string.split("[=]");
System.out.println(splitString[1] + " = " + splitString[2]);
or, much more simply, make that one small edit that #retrodrone posted
OK I managed to resolve this issue, for anyone else who cares. The problem with the code is that the Node needs to be cast to an Element before you can get the tag name out of it in this manner. Therefore:
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(XMLstring));
Document doc = db.parse(is);
NodeList nodes = doc.getElementsByTagName("client-details");
Node node = nodes.item(0);
NodeList client_details = node.getChildNodes();
Element elementary;
for (int i = 0; i < client_details.getLength(); i++) {
if(client_details.item(i).getNodeType() == Node.ELEMENT_NODE) {
elementary = (Element) client_details.item(i);
System.out.println(elementary.getTagName()+" = "+getTextContents(client_details.item(i)));
}
}
}
Which produces the desired result, minus that "#text" bollocks :)
testing-mode = false
name = testman
age = 30
Notice the new "if" statement I added inside the for loop and the cast of the node to an element before calling getNodeName, which does work for Elements.
I have an XML file that I am trying to search using Java. I just need to find an element by its Tag name and then find that Tag's value. So for example:
I have this XML file:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="https://company.com/test/xslt/processing_report.xslt"?>
<Certificate xmlns="urn:us:net:exchangenetwork:Company">
<Value1>Veggie</Value1>
<Value2>Fruits</Value2>
<type1>Apple</type1>
<FindME>Red</FindME>
<Value3>Bread</Value3>
</Certificate>
I want to find the value inside of the FindME Tag. I can't use XPath because different files can have different structures, but they always have a FindME tag. Lastly I am looking for the simplest piece of code, I do not care much about performance. Thank you
Here is the code:
XPathFactory f = XPathFactory.newInstance();
XPathExpression expr = f.newXPath().compile(
"//*[local-name() = 'FindME']/text()");
DocumentBuilderFactory domFactory = DocumentBuilderFactory
.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse("src/test.xml"); //your XML file
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
System.out.println(nodes.getLength());
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(nodes.item(i).getNodeValue());
}
Explained :
//* - match any element node - no matter where they are
local-name() = 'FindME' - where local name - i.e; not the full path - matches 'FindME'
text() - get the node value.
I think you need to read up on XPath because it can very easily solve this problem. So can using getElementsByTagName in the DOM API.
You can still use XPath. All you need to do is use //FindMe (read here on // usage) expression. This finds a the "FindMe" elements from any where in the xml irrespective of its parent or path from the root.
If you are using namespaces then make sure you are making the parser aware of that
String findMeVal = null;
InputStream is = //...
XmlPullParser parser = //...
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
parser.setInput(is, null);
int event;
while (XmlPullParser.END_DOCUMENT != (event = parser.next())) {
if (event == XmlPullParser.START_TAG) {
if ("FindME".equals(parser.getName())) {
findMeVal = parser.nextText();
break;
}
}
}
I am quite new to XML parsing and I have my method of parsing XML. Only that method is for simple XML layouts with just 1 child node.
I now have to parse an XML file with childs that have childs that have childs (got it :)?)
This is the parse-method I have now:
protected Map<String, Maatschappij> getAutopechTel() {
Map<String, Maatschappij> telVoorAutopech = new HashMap<String, Maatschappij>();
try {
DocumentBuilder builder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
Document doc = builder.parse(getAssets().open("autopech.xml"));
NodeList nl = doc.getElementsByTagName("dienst");
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
Maatschappij maat = new Maatschappij();
maat.setNaam(Xml.innerHtml(Xml.getChildByTagName(node, "naam")));
maat.setTel(Xml.innerHtml(Xml.getChildByTagName(node, "tel")));
telVoorAutopech.put(maat.getTel(), maat);
}
} catch (Exception e) {
}
return telVoorAutopech;
}
How must I adjust this in order to parse this type of XML file:
<Message>
<Service>Serviceeee</Service>
<Owner>Bla</Owner>
<LocationFeedTo>Too</LocationFeedTo>
<Location>http://maps.google.com/?q=52.390001,4.890145</Location>
<Child1>
<Child1_1>
<Child1_1_1>ANWB</Child1_1_1>
</Child1_1>
</Child1>
<Message>
You can use SAXParser to parse XML in Android :
Here is a detailed tutorial with example and also another one here by IBM developerWorks.
DOM Parser is slow and consume a lot
memory if it load a XML document
which contains a lot of data. Please
consider SAX parser as solution for
it, SAX is faster than DOM and use
less memory.
Try this one out but I haven't tested this code yet. It recursively traverses all the nodes and adds which are ELEMENT_NODE to the Vector<Node>.
public void traverseNodes(Node node, Vector<Node> nodeList)
{
if(node.getNodeType() == Node.ELEMENT_NODE)
{
nodeList.add(node);
if(node.getChildNodes().getLength() >= 1)
{
NodeList childNodeList = node.getChildNodes();
for(int nodeIndex = 1;nodeIndex < childNodeList.getLength(); nodeIndex++)
{
traverseNodes(childNodeList.item(nodeIndex),nodeList);
}
}
}
}