Sax parser issues in android - java

I'm trying to parse a xml using SAX parser. The code works fine on pc but on android the elements doesn't get added to list .
In the code i'm trying to add the data within the tags sunrise & sunset onto the list array
In public
void endElement(..) {}
System.out.println("size of list " + timeLst.size()); //Always shows 0 in android
Below is the code..
TimeServiceParser tsp = new TimeServiceParser();
tsp.parseDocument(new URL("http://www.earthtools.org/sun/47.566667/-52.716667/14/3/99/1"));
tsp.printData();
public class TimeService extends DefaultHandler {
public void parseDocument(URL sourceUrl) {
SAXParserFactory spf = SAXParserFactory.newInstance();
try{
SAXParser sp = spf.newSAXParser();
InputStream is = sourceUrl.openStream();
sp.parse(is, this);
}catch(SAXException se) {
...
}
}
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
tempVal = "";
if(qName.equalsIgnoreCase("sunrise")) {
tempTimeData = new TimeData();
}
}
public void endElement(String uri, String localName, String qName) throws SAXException {
if(qName.equalsIgnoreCase("sunrise")) {
tempTimeData.setSunriseTime(tempVal);
timeLst.add(tempTimeData);
}else if(qName.equalsIgnoreCase("sunset")) {
if(tempTimeData!=null) {
TimeData t = (TimeData)(timeLst.get(0));
t.setSunsetTime(tempVal);
}
}
System.out.println("size of list " + timeLst.size()); //Always shows 0 in android
}
public void characters(char[] ch, int start, int length) throws SAXException {
tempVal = new String(ch , start , length);
}
public void printData() {
Iterator<TimeData> it = timeLst.listIterator();
while(it.hasNext()) {
TimeData td = (TimeData)(it.next());
System.out.println(td.getSunriseTime());
System.out.println(td.getSunsetTime());
}
}
}

Related

Turn java XML SAX Parser to web app Tomcat

I've got a java SAX Parser for XML (we set the date, make URL reqest for this date and parse XML file). Now I need to turn this code to web app in Tomcat. I've imported all nessessary libraries, created artefacts, but don't know how to change code itself.\
Here is initial code
Handler:
public class UserHandler extends DefaultHandler {
boolean bName = false;
boolean bValue = false;
String result=" ";
#Override
public void startElement(String uri,
String localName, String qName, Attributes attributes) throws SAXException {
if (qName.equalsIgnoreCase("Valute")) {
String CharCode = attributes.getValue("CharCode");
} else if (qName.equalsIgnoreCase("Name")) {
bName = true;
} else if (qName.equalsIgnoreCase("Value")) {
bValue = true;
}
}
#Override
public void endElement(String uri,
String localName, String qName) throws SAXException {
if (qName.equalsIgnoreCase("Valute")) {
System.out.print(" ");
}
}
#Override
public void characters(char ch[], int start, int length) throws SAXException {
if (bName) {
result=(new String(ch, start, length)+" ");
bName = false;
} else if (bValue) {
result=result+(new String(ch, start, length));
bValue = false;
System.out.print(result);
}
}
}
Main:
public static void main(String[] args) throws MalformedURLException {
//Set the date dd.mm.yyyy
String date="12.08.2020";
String link ="http://www.cbr.ru/scripts/XML_daily.asp?date_req=";
URL url =new URL(link);
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
UserHandler userHandler = new UserHandler();
saxParser.parse(String.valueOf(url+date), userHandler);
} catch (Exception e) {
e.printStackTrace();
}
}
}

sax parsing - mapping nested tags into main tag

I want to use sax parser for a large xml file. Handler looks like this:
DefaultHandler handler = new DefaultHandler() {
String temp;
HashSet < String > xml_Elements = new LinkedHashSet < String > ();
HashMap < String, Boolean > xml_Tags = new LinkedHashMap < String, Boolean > ();
HashMap < String, ArrayList < String >> tags_Value = new LinkedHashMap < String, ArrayList < String >> ();
//###startElement#######
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
xml_Elements.add(qName);
for (String tag: xml_Elements) {
if (qName == tag) {
xml_Tags.put(qName, true);
}
}
}
//###########characters###########
public void characters(char ch[], int start, int length) throws SAXException {
temp = new String(ch, start, length);
}
//###########endElement############
public void endElement(String uri, String localName,
String qName) throws SAXException {
if (xml_Tags.get(qName) == true) {
if (tags_Value.containsKey(qName)) {
tags_Value.get(qName).add(temp);
tags_Value.put(qName, tags_Value.get(qName));
} else {
ArrayList < String > tempList = new ArrayList < String > ();
tempList.add(temp);
//tags_Value.put(qName, new ArrayList<String>());
tags_Value.put(qName, tempList);
}
//documentWriter.write(qName+":"+temp+"\t");
for (String a: tags_Value.keySet()) {
try {
documentWriter.write(tags_Value.get(a) + "\t");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
xml_Tags.put(qName, false);
}
tags_Value.clear();
}
};
My xml is like :
<TermInfo>
<A>1/f noise</A>
<B>Random noise</B>
<C>Accepted</C>
<D>Flicker noise</D>
<F>Pink noise</F>
<I>1-f</I>
<I>1/f</I>
<I>1/f noise</I>
<I>1:f</I>
<I>flicker noise</I>
<I>noise</I>
<I>pink noise</I>
<ID>1</ID>
</TermInfo>
<TermInfo>
<A>3D printing</A>
<B>Materials fabrication</B>
<C>Accepted</C>
<D>3d printing</D>
<F>2</F>
<I>three dimension*</I>
<I>three-dimension*</I>
<I>3d</I>
<I>3-d</I>
<I>3d*</I>
</TermInfo>
I wanted to cluster all nested tags under Tag A.
ie for each A.. its B,C,D and I together.. etc. But using the above handler the output is like A-B-C-D-I-I-etc . Can I make one object for each A and add other elements into it. How can I include this..
I think this is along the lines of what you are asking for. It creates a List of HashMap objects. Every time it starts a TermInfo, it creates a new HashMap. Each endElement inside TermInfo puts a value into the Map. When endElement is TermInfo, it sets fieldMap to null so no intermediate tags are added. "TermInfo" represents A from your description.
public class TestHandler extends DefaultHandler
{
Map<String, String> fieldMap = null;
List<Map<String, String>> tags_Value = new ArrayList<Map<String, String>>();
String temp;
// ###startElement#######
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException
{
if (localName.equals("TermInfo")) // A
{
fieldMap = new HashMap<String, String>();
tags_Value.add(fieldMap);
}
}
// ###########characters###########
public void characters(char ch[], int start, int length)
throws SAXException
{
temp = new String(ch, start, length);
}
// ###########endElement############
public void endElement(String uri, String localName, String qName)
throws SAXException
{
if (fieldMap != null)
{
if (!localName.equals("TermInfo")) // A
{
fieldMap.put(localName, temp);
}
else
{
//END of TermInfo
fieldMap = null;
}
}
}

Java XML Parsing using SAXParser

I have an API.When we request it will produce XML as response data
The below is the API Response for Description field:
<parameter>
<name>description</name>
<value>Description Description</value>
</parameter>
The below is the code to parse XML File(SAXPraser)
public class WorkOrderDataHandler extends DefaultHandler {
public WorkOrderDataHandler() {
parameterList = new ArrayList<Parameter>();
contentsOfTheCurrentTag = new StringBuilder();
}
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if (qName.equalsIgnoreCase("Details")) {
ticketData = new TicketInterMediateData();
}
if (qName.equalsIgnoreCase("parameter")) {
parameter = new Parameter();
}
}
public void endElement(String uri, String localName, String qName)
throws SAXException {
int length = contentsOfTheCurrentTag.length();
if (qName.equalsIgnoreCase("name")) {
parameter.setName(contentsOfTheCurrentTag.toString().trim());
}
if (qName.equalsIgnoreCase("value")) {
parameter.setValue(contentsOfTheCurrentTag.toString().trim());
}
if (qName.equalsIgnoreCase("parameter")) {
parameterList.add(parameter);
}
if (qName.equalsIgnoreCase("parameter")) {
if ("workorderid".equals(parameter.getName())) {
ticketData.setIt360ticketid(Integer.parseInt(parameter
.getValue().trim()));
}
else if ("description".equals(parameter.getName())) {
System.out.println("Handler desc"+ parameter.getValue());//DescriptionDescriptionÂ
ticketData.setDescription((parameter.getValue()));
}
}
contentsOfTheCurrentTag.delete(0, length);
}
public void characters(char ch[], int start, int length)
throws SAXException {
contentsOfTheCurrentTag.append(ch, start, length);
}
}
Output:
When i tried to parse the description field. i am getting the output as DescriptionDescriptionÂ
Could anyone please help

null pointer exception using SAX XML Parser

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.

Reading nested tags with sax parser

i am trying to read a xml file with following tag, but the sax parser is unable to read nested tags like
<active-prod-ownership>
<ActiveProdOwnership>
<Product code="3N3" component="TRI_SCORE" orderNumber="1-77305469" />
</ActiveProdOwnership>
</active-prod-ownership>
here is the code i am using
public class LoginConsumerResponseParser extends DefaultHandler {
// ===========================================================
// Fields
// ===========================================================
static String str="default";
private boolean in_errorCode=false;
private boolean in_Ack=false;
private boolean in_activeProdOwnership= false;
private boolean in_consumerId= false;
private boolean in_consumerAccToken=false;
public void startDocument() throws SAXException {
Log.e("i am ","in start document");
}
public void endDocument() throws SAXException {
// Nothing to do
Log.e("doc read", " ends here");
}
/** Gets be called on opening tags like:
* <tag>
* Can provide attribute(s), when xml was like:
* <tag attribute="attributeValue">*/
public void startElement(String namespaceURI, String localName,
String qName, Attributes atts) throws SAXException {
if(localName.equals("ack")){
in_Ack=true;
}
if(localName.equals("error-code")){
in_errorCode=true;
}
if(localName.equals("active-prod-ownership")){
Log.e("in", "active product ownership");
in_activeProdOwnership=true;
}
if(localName.equals("consumer-id")){
in_consumerId= true;
}
if(localName.equals("consumer-access-token"))
{
in_consumerAccToken= true;
}
}
/** Gets be called on closing tags like:
* </tag> */
public void endElement(String namespaceURI, String localName, String qName)
throws SAXException {
if(localName.equals("ack")){
in_Ack=false;
}
if(localName.equals("error-code")){
in_errorCode=false;
}
if(localName.equals("active-prod-ownership")){
in_activeProdOwnership=false;
}
if(localName.equals("consumer-id")){
in_consumerId= false;
}
if(localName.equals("consumer-access-token"))
{
in_consumerAccToken= false;
}
}
/** Gets be called on the following structure:
* <tag>characters</tag> */
public void characters(char ch[], int start, int length) {
if(in_Ack){
str= new String(ch,start,length);
}
if(str.equalsIgnoreCase("success")){
if(in_consumerId){
}
if(in_consumerAccToken){
}
if(in_activeProdOwnership){
str= new String(ch,start,length);
Log.e("active prod",str);
}
}
}
}
but on reaching the tag in_activeProdOwnersip read only "<" as the contents of the tag
please help i need to the whole data to be read
The tags in your XML file and parser does not match. I think you are mixing-up tags with attribute names. Here is the code that correctly parses your sample XML:
public class LoginConsumerResponseParser extends DefaultHandler {
public void startDocument() throws SAXException {
System.out.println("startDocument()");
}
public void endDocument() throws SAXException {
System.out.println("endDocument()");
}
public void startElement(String namespaceURI, String localName,
String qName, Attributes attrs)
throws SAXException {
if (qName.equals("ActiveProdOwnership")) {
inActiveProdOwnership = true;
} else if (qName.equals("Product")) {
if (!inActiveProdOwnership) {
throw new SAXException("Product tag not expected here.");
}
int length = attrs.getLength();
for (int i=0; i<length; i++) {
String name = attrs.getQName(i);
System.out.print(name + ": ");
String value = attrs.getValue(i);
System.out.println(value);
}
}
}
public void endElement(String namespaceURI, String localName, String qName)
throws SAXException {
if (localName.equals("ActiveProdOwnership"))
inActiveProdOwnership = false;
}
public void characters(char ch[], int start, int length) {
}
public static void main(String args[]) throws Exception {
String xmlFile = args[0];
File file = new File(xmlFile);
if (file.exists()) {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
DefaultHandler handler = new Test();
parser.parse(xmlFile, handler);
}
else {
System.out.println("File not found!");
}
}
private boolean inActiveProdOwnership = false;
}
A sample run will produce the following output:
startDocument()
code: 3N3
component: TRI_SCORE
orderNumber: 1-77305469
endDocument()
I suspect this is what's going wrong:
new String(ch,start,length);
Here, you're passing a char[] to the String constructor, but the constructor is supposed to take a byte[]. The end result is you get a mangled String.
I suggest instead that you make the str field a StringBuilder, not a String, and then use this:
builder.append(ch,start,length);
You then need to clear the StringBuilder each time startElement() is called.

Categories