i try to build an application with xml parser.
ex : http://www.androidpeople.com/android-xml-parsing-tutorial-using-saxparser
but i want to parse xml file from EditText, how it work ?
Change this line:
xr.parse(new InputSource(sourceUrl.openStream()));
to
String xmlString = editText.getText().toString();
StringReader reader = new StringReader(xmlString);
xr.parse(new InputSource(reader));
You have several ways to parse XML, the most widely used being SAX and DOM. The choice is quite strategical as explained in this paper.
Here is a short explanation of SAX:
You will need some imports:
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;
import android.util.Xml;
Create your own XML SAX DefaultHandler:
class MySaxHandler extends DefaultHandler {
// Override the methods of DefaultHandler that you need.
// See [this link][3] to see these methods.
// These methods are going to be called while the XML is read
// and will allow you doing what you need with the content.
// Two examples below:
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
// This is called each time an openeing XML tag is read.
// As the tagname is passed by parameter you know which tag it is.
// You also have the attributes of the tag.
// Example <mytag myelem="12"> will lead to a call of
// this method with the parameters:
// - localName = "mytag"
// - attributes = { "myelem", "12" }
}
public void characters(char[] ch, int start, int length) throws SAXException {
// This is called each time some text is read.
// As an example, if you have <myTag>blabla</myTag>
// this will be called with the parameter "blabla"
// Warning 1: this is also called when linebreaks are read and the linebreaks are passed
// Warning 2: you have to memorize the last open tag to determine what tag this text belongs to (I usually use a stack).
}
}
Extract the XML as a String from the EditText. Let's call it xmlContent
Create and initialize your XML parser:
final InputStreamReader reader = new InputStreamReader(new ByteArrayInputStream(xmlContent.getBytes()));
final MySaxHandler handler = new MySaxHandler();
And then, make the XML content to be read by the parser. This will lead your MySaxHandler to have its various method called while the reading is in progress.
Xml.parse(reader, handler);
Related
I have a string "© 2015" in my HTML document. I'm parsing the HTML document using TagHandler.
opinion_description.setText(Html.fromHtml(description, this, new Html.TagHandler() {
#Override
public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader) {
}
}));
I'm not handling anything inside handleTag(), as the tagHandler itself is handling everything. But it's not parsing the above mentioned string. So, I'm manually replacing the string with "".
if(description.contains("Ã-Â"))
description.replace("Ã-Â","");
But it's not working. Is there any better way to parse this string.
Thanks in advance.
I am new to andriod programming can any help on how to parse a xml file and put the data into a spinner please help.
The XML file link is as follows :http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml
Thanks
since your xml file is large is better that use sax parser .for using from sax parser you should use DeafaultHandler class and override its methods and in its startElement method you should write thing same following for get values:
public void startElement(String arg0, String localName, String arg2,
Attributes attributes) throws SAXException {
currentElement = true;
if (localName.equals("marker")) {
String currency = attributes.getValue("currency ");
String rat= attributes.getValue("rat");
//and ...
}
}
}
I am currently creating my first android application
i never used it before
What i need is to read xml file from the internet and put it in a list
( to read this xml http://pollsdb.com/test.txt and put the results in list )
i will appreciate if someone can post a code that works
XML Pull Parser is an interface that defines parsing functionality provided in XMLPULL V1 API .
There are following different kinds of parser depending on which features are set:
non-validating parser as defined in XML 1.0 spec when FEATURE_PROCESS_DOCDECL is set to true
validating parser as defined in XML 1.0 spec when FEATURE_VALIDATION is true (and that implies that FEATURE_PROCESS_DOCDECL is true)
when FEATURE_PROCESS_DOCDECL is false (this is default and if different value is required necessary must be changed before parsing is started) then parser behaves like XML 1.0 compliant non-validating parser under condition that no DOCDECL is present in XML documents (internal entites can still be defined with defineEntityReplacementText()). This mode of operation is intended for operation in constrained environments such as J2ME.
There are two key methods: next() and nextToken(). While next() provides access to high level parsing events, nextToken() allows access to lower level tokens.
The current event state of the parser can be determined by calling the getEventType() method. Initially, the parser is in the START_DOCUMENT state.
The method next() advances the parser to the next event. The int value returned from next determines the current parser state and is identical to the value returned from following calls to getEventType ().
Th following event types are seen by next()
START_TAG
An XML start tag was read.
TEXT
Text content was read; the text content can be retrieved using the getText() method. (when in validating mode next() will not report ignorable whitespace, use nextToken() instead)
END_TAG
An end tag was read
END_DOCUMENT
No more events are available
after first next() or nextToken() (or any other next*() method) is called user application can obtain XML version, standalone and encoding from XML declaration in following ways:
version: getProperty("http://xmlpull.org/v1/doc/properties.html#xmldecl-version") returns String ("1.0") or null if XMLDecl was not read or if property is not supported
standalone: getProperty("http://xmlpull.org/v1/doc/properties.html#xmldecl-standalone") returns Boolean: null if there was no standalone declaration or if property is not supported otherwise returns Boolean(true) if standalone="yes" and Boolean(false) when standalone="no"
encoding: obtained from getInputEncoding() null if stream had unknown encoding (not set in setInputStream) and it was not declared in XMLDecl
A minimal example for using this API may look as follows:
import java.io.IOException;
import java.io.StringReader;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
public class SimpleXmlPullApp
{
public static void main (String args[])
throws XmlPullParserException, IOException
{
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput( new StringReader ( "<foo>Hello World!</foo>" ) );
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if(eventType == XmlPullParser.START_DOCUMENT) {
System.out.println("Start document");
} else if(eventType == XmlPullParser.START_TAG) {
System.out.println("Start tag "+xpp.getName());
} else if(eventType == XmlPullParser.END_TAG) {
System.out.println("End tag "+xpp.getName());
} else if(eventType == XmlPullParser.TEXT) {
System.out.println("Text "+xpp.getText());
}
eventType = xpp.next();
}
System.out.println("End document");
}
}
The above example will generate the following output:
Start document
Start tag foo
Text Hello World!
End tag foo
EDIT THE CODE TO YOUR NEEDS :)
I am developing an application where I want to parse a xml. my node structure ia as follow
<MainNode title="firstNode">
<Subnode>value</Subnode>
</MainNode>
Now I want to read title of first node but I don't get it how to read this. Does any one done this before. Please give some example.
Thank You
Note--Below code tried
public void startElement(String uri, String localName, String name,
Attributes attributes) throws SAXException {
super.startElement(uri, localName, name, attributes);
if (localName.equalsIgnoreCase(MAIN)){
this.RegisterMessage = new RegisterMessage();
Log.v("AttValue",attributes.getValue("title").toString());
}
}
I tested this code in debugger but control doesn't came to if statement.
Note:-- SAX Parser is looking more complicated for me so I just shifted for BaseFeedParser it not solved my question but it is working as I want & still the question is same how to read nodes attribute in BaseFeedParser.
Inside your handler class, implement parsing for MainNode as:
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if (localName.equals("MainNode"))
{
/** Get attribute value */
String strTitle = attributes.getValue("title");
Log.i("Title",strTitle);
}
}
You can follow my article series on Android XML : http://xjaphx.wordpress.com/2011/10/09/android-xml-adventure-parsing-data-with-saxparser/
Very easy for beginners, full source code provided, line by line instructions :)
I am new to programming, so to start with correct me if I am wrong in the paragragh below :
There is mainly three xml parsers for use in Android : Sax, Dom, and XmlPullParser. That last option, while existing as an external ressource. Is "in the core" of Android, thus working faster, but the functionnalities are limited
Ok here is my Question I slightly modified the code provided in the link below
http://developer.android.com/reference/org/xmlpull/v1/XmlPullParser.html
I did the following :
import java.io.IOException;
import java.io.StringReader;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
public class xmlPParser
{
public String texte;
public xmlPParser (String arg)
throws XmlPullParserException, IOException
{
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput( new StringReader ( arg ) );
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT)
{
//if(eventType == XmlPullParser.START_DOCUMENT) { System.out.println("Start document");}
// else if(eventType == XmlPullParser.START_TAG) { System.out.println("Start tag "+xpp.getName()); }
//else if(eventType == XmlPullParser.END_TAG) { System.out.println("End tag "+xpp.getName()); }
if(eventType == XmlPullParser.TEXT){ texte = xpp.getText(); } //{ System.out.println("Text "+xpp.getText());}
eventType = xpp.next();
}
//System.out.println("End document");
}
public String getTexte()
{
String returnTexte = texte;
return returnTexte;
}
}
In another java file, I can call the parser in the following way :
public xmlPParser myxpp;
...
myxpp = new xmlPParser("<foo>Hi five !!</foo>");
On that last line : I would like to be able to ask the parser to go to a file, instead of passing a string to it. how would i do that ?
I am not sure how to make use of this posting
Does getResources().getXml() supposes I am using the Android pullParser which I am not sure to be using now ?
XmlPullParser is not really a parser, it is an interface to a type of parser, called a "pull" parser.
The function getResources().getXml() returns an implementation of XmlPullParser for "parsing" XML resources. This is not a real XML parser -- in fact the original XML file was parsed at build time before being built into your app, and what this "XML parser" is doing is just returning the pre-digested XML structure as you call its API. This is the fastest "XML" parser available on Android (because it is not really parsing anything), but requires that the XML document be compiled as part of building your app.
The other implementation of XmlPullParser that you get from XmlPullParserFactory.newInstance() is not "limited" -- this implementation is full-featured, and can parse any raw XML document you give to it.
At least at one time (not sure if this is still the case), both the SAX parser and the parser returned by XmlPullParserFactory.newInstance() are actually built on the same underlying implementation, which is expat. The expat parser is a "push" parser (that is the same model as SAX), so the most efficient way to use it is with the SAX API. The XmlPullParser version has some more overhead from SAX since it needs to turn the underlying push semantics into a pull interface.
If it helps -- push means that it pushes the parsed data to you (callbacks you implement giving you each tag and other document element), while pull means you make calls to the parser to retrieve each element.