I am tryin to get rss feed using xml parsing and
I am getting problem while parsing xml data using SAXParser
I have tried something like
In my MainActivity.java
try{
/****** Creating a new instance of the SAX parser ****************/
SAXParserFactory saxPF = SAXParserFactory.newInstance();
SAXParser saxParser = saxPF.newSAXParser();
XMLReader xmlReader = saxParser.getXMLReader();
URL url = new URL("http://ibnlive.in.com/ibnrss/rss/world/world.xml");
myXMLHandler = new FeedsXMLHandler();
xmlReader.setContentHandler(myXMLHandler);
xmlReader.parse(new InputSource(url.openStream()));
}catch (Exception e) {
e.printStackTrace();
}
I am retriving data from my handler using
ArrayList<FeedsItems> feedsData = myXMLHandler.getXMLData();
Log.v("size",Integer.toString(feedsData.size()));
Here its showing size as zero.
My FeedsXMLHandler.java
private ArrayList<FeedsItems> dataArray = new ArrayList<FeedsItems>();
private FeedsItems data = null;
#Override
public void startElement(String uri, String localName, String qName,Attributes attributes) throws SAXException
{
elementValue = "";
elementOn = true;
if (localName.equalsIgnoreCase("rss"))
{
// data = new FeedsItems();
}
else if (localName.equalsIgnoreCase("item"))
{
data = new FeedsItems();
Log.v("Item","I am in item block");
}
else if (localName.equalsIgnoreCase("description"))
{
bufferDesc = new StringBuilder();
elementOn = true;
}
else if (localName.equalsIgnoreCase("title"))
{
bufferTitle = new StringBuilder();
elementOn = true;
}
else if(localName.equalsIgnoreCase("link"))
{
bufferLink = new StringBuilder();
elementOn = true;
}
}
/*********** Method will be called when the tags of the XML end **************/
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
elementOn = false;
/*** Sets the values after retrieving the values from the XML tags ******/
if (localName.equalsIgnoreCase("title"))
{
elementOn = false;
data.setTitle(bufferTitle.toString());
bufferTitle.delete(0,bufferTitle.length());
}
else if (localName.equalsIgnoreCase("link")){
elementOn = false;
data.setFeedsUrl(bufferLink.toString());
bufferLink.delete(0,bufferLink.length());
}
else if (localName.equalsIgnoreCase("description")){
elementOn = false;
data.setDescription(bufferDesc.toString());
bufferDesc.delete(0, bufferDesc.length());
}
else if (localName.equalsIgnoreCase("item")){
dataArray.add(data);
}
}
I am not able to understand whats wrong in it. I have already implemented xml parsing using SAXParser in this method. Any help or suggestion will be welcome
Related
I have an XML and inside it I want to modify for specific nodes the value of link attribute using SAXParser.
I did found https://stackoverflow.com/a/51662488/9681353 and I used Attributes2Impl for my case.
What I have so far:
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
UpdateLinksHandler linksHandler = new UpdateLinksHandler();
saxParser.parse(xml, linksHandler);
#Override
public void startElement(String uri, String key, String qName, Attributes attributes) throws SAXException {
if (qName.equalsIgnoreCase(USEROBJECT)) {
String link = attributes.getValue("link");
if (link != null) {
Attributes2 attrs = (Attributes2) attributes;
Attributes2Impl newAttrs = new Attributes2Impl();
for (int i = 0; i < attrs.getLength(); i++) {
if (attrs.isSpecified(i)) {
String type = attrs.getType(i);
String value = attrs.getValue(i);
String name = attrs.getQName(i);
if (name == "link") {
value = modifyLink(value);
}
newAttrs.addAttribute(null, null, name, type, modifyLink(value));
}
}
super.startElement(uri, key, qName, newAttrs);
}
}
But I don't know if my approach is correct or how I should get my modified xml. Or SAXParser is just for reading purposes?
Thanks
I have a simple xml and want to retrieve the value held in the 'String' which is either True or False. There are lots of suggested methods which look very complex! What would be the best way to do this?
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">"True"</string>
I am able to read the xml into an xmlReader as below.
XMLReader xmlReader = SAXParserFactory.newInstance()
.newSAXParser().getXMLReader();
InputSource source = new InputSource(new StringReader(response.toString()));
xmlReader.parse(source);
How would I now get the value out of the reader?
You will first need to define a Handler :
public class MyElementHandler extends DefaultHandler {
private boolean isElementFound = false;
private String value;
public String getValue() {
return value;
}
#Override
public void startElement(String uri, String localName, String qName, Attributes attributes) {
if (qName.equals("elem")) {
isElementFound = true;
}
}
#Override
public void endElement(String uri, String localName, String qName) {
if (qName.equals("elem")) {
isElementFound = false;
}
}
#Override
public void characters(char ch[], int start, int length) {
if (isElementFound) {
value = new String(ch).substring(start, start + length);
}
}
}
Then, the you parse your xml as follows :
String xml = response.toString();
XMLReader xmlReader = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
InputSource source = new InputSource(new StringReader(xml));
//-- create handlers
MyAttributeHandler handler = new MyAttributeHandler();
xmlReader.setContentHandler(handler);
xmlReader.parse(source);
System.out.println("value = " + handler.getValue());
More general question about sax parsing.
Here one does not need XML. A two-liner:
String xmlContent = response.toString();
String value = xmlContent.replaceFirst("(?sm)^.*<string[^>]*>([^<]*)<.*$", "$1");
if (value == xmlContent) { // No replace
throw new IllegalStateException("Not found");
}
boolean result = Boolean.valueOf(value.trim().toLowerCase());
With XML one could do:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(inputSource);
String xml = doc.getDocumentElement().getTextContent();
CODE:
public void parse(byte[] payload)
{
try
{
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
DefaultHandler handler = new DefaultHandler()
{
boolean eid = false;
boolean msg_id = false;
boolean date_time = false;
boolean temp = false;
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException
{
if (qName.equalsIgnoreCase("eid"))
{
eid = true;
}
if (qName.equalsIgnoreCase("msg_id"))
{
msg_id = true;
}
if (qName.equalsIgnoreCase("date_time"))
{
date_time = true;
}
if (qName.equalsIgnoreCase("temperature"))
{
temp = true;
}
}
public void characters(char ch[], int start, int length) throws SAXException
{
if (eid)
{
XMLMessagePacket.this.eid = new String(ch, start, length);
eid = false;
}
if (msg_id)
{
XMLMessagePacket.this.msgId = new String(ch, start, length);
msg_id = false;
}
if (date_time)
{
XMLMessagePacket.this.time = new String(ch, start, length);
date_time = false;
}
if (temp)
{
XMLMessagePacket.this.temperature.parseDouble(new String(ch, start, length));
temp = false;
}
}
};
saxParser.parse(new ByteArrayInputStream(payload), handler);
}
catch (Exception e)
{
e.printStackTrace();
}
}
XML
<?xml version="1.0"?>
<event>
<eid>345345</eid>
<msg_id>3242</msg_id>
<date_time>11342345</date_time>
<temperature>100</temperature>
</event>
Problem:
org.xml.sax.SAXParseException: Content is not allowed in prolog.
Just something to check: a friend once fought this "bug" all night. Is it possible your file has a Byte Order Mark at the beginning? Parsing it as a String might make it disappear. The default encoding for XML is UTF-8 (which does not require a BOM). It's just possible you're getting tripped up by something you can't see.
I get the xml repsonse for http request. I store it as a string variable
String str = in.readLine();
And the contents of str is:
<response>
<lastUpdate>2012-04-26 21:29:18</lastUpdate>
<state>tx</state>
<population>
<li>
<timeWindow>DAYS7</timeWindow>
<confidenceInterval>
<high>15</high>
<low>0</low>
</confidenceInterval>
<size>0</size>
</li>
</population>
</response>
I want to assign tx, DAYS7 to variables. How do I do that?
Thanks
Slightly modified code from http://www.mkyong.com/java/how-to-read-xml-file-in-java-sax-parser/
public class ReadXMLFile {
// Your variables
static String state;
static String timeWindow;
public static void main(String argv[]) {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
// Http Response you get
String httpResponse = "<response><lastUpdate>2012-04-26 21:29:18</lastUpdate><state>tx</state><population><li><timeWindow>DAYS7</timeWindow><confidenceInterval><high>15</high><low>0</low></confidenceInterval><size>0</size></li></population></response>";
DefaultHandler handler = new DefaultHandler() {
boolean bstate = false;
boolean tw = false;
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if (qName.equalsIgnoreCase("STATE")) {
bstate = true;
}
if (qName.equalsIgnoreCase("TIMEWINDOW")) {
tw = true;
}
}
public void characters(char ch[], int start, int length) throws SAXException {
if (bstate) {
state = new String(ch, start, length);
bstate = false;
}
if (tw) {
timeWindow = new String(ch, start, length);
tw = false;
}
}
};
saxParser.parse(new InputSource(new ByteArrayInputStream(httpResponse.getBytes("utf-8"))), handler);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("State is " + state);
System.out.println("Time windows is " + timeWindow);
}
}
If you're running this as a part of some process you might want to extend the ReadXMLFile from DefaultHandler.
I am using the SAX Parser for XML Parsing. The problem is if I print, everything is fine. However, If I want to save anything, I get this error message (with the typos):
"XML Pasing Excpetion = java.lang.NullPointerException"
My code is given below:
Parser code:
try {
/** Handling XML */
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
/** Send URL to parse XML Tags */
URL sourceUrl = new URL(
"http://50.19.125.224/Demo/VeryGoodSex_and_the_City_S6E6.xml");
/** Create handler to handle XML Tags ( extends DefaultHandler ) */
MyXMLHandler myXMLHandler = new MyXMLHandler();
xr.setContentHandler((ContentHandler) myXMLHandler);
xr.parse(new InputSource(sourceUrl.openStream()));
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
Object to hold XML parsed Info:
public class ParserObject {
String name=null;
String description=null;
String bitly=null; //single
String productLink=null;//single
String productPrice=null;//single
Vector<String> price=null;
}
Handler class:
static ParserObject[] xmlDataObject = null;
public void endElement(String uri, String localName, String qName)
throws SAXException {
currentElement = false;
if (qName.equalsIgnoreCase("title"))
{
xmlDataObject[index].name=currentValue;
}
else if (qName.equalsIgnoreCase("artist"))
{
xmlDataObject[index].artist=currentValue;
}
}
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
currentElement = true;
if (qName.equalsIgnoreCase("allinfo"))
{
System.out.println("started");
}
else if (qName.equalsIgnoreCase("tags"))
{
insideTag=1;
}
}
public void characters(char[] ch, int start, int length)
throws SAXException {
if (currentElement) {
currentValue = new String(ch, start, length);
currentElement = false;
}
}
Your ParserObject array i.e xmlDataObject is having null value thats is why it is showing null pointer exception. This is my View and it might be wrong but once check it too.