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
Related
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();
}
}
}
I use SAX XML Parser and when I use:
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException
I can get attributes.
But I need get attributes from public void endElement
To parse something like that:
<item name="test" value="somedata" />
Code:
public class SAXXMLHandler extends DefaultHandler {
private ArrayList<itemsList> items;
private String tempVal;
private itemsList tempEmp;
private PackageManager manager;
private String packName;
public SAXXMLHandler(PackageManager manager, String packName) {
items = new ArrayList<itemsList>();
this.manager = manager;
this.packName = packName;
}
public void characters(char[] ch, int start, int length)
throws SAXException {
tempVal = new String(ch, start, length);
}
// Event Handlers
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
Log.d("INFO", "startElement " + localName + ", " + qName + ", " + attributes);
// reset
tempVal = "";
if (qName.equalsIgnoreCase("item")) {
// create a new instance of employee
tempEmp = new itemsList();
tempEmp.setName(attributes.getValue("name"));
}
}
public void endElement(String uri, String localName, String qName)
throws SAXException {
Log.d("INFO", "endElement " + localName + ", " + qName);
}
And don't logcat from startElement
UPDATE
I use in Fragment:
SAXXMLHandler handler = new SAXXMLHandler();
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
saxParser.parse(asset, handler);
items = SAXXMLHandler.icons;
Util.l(String.valueOf(SAXXMLHandler.icons.size())); //log
for(itemList item:SAXXMLHandler.icons)
{
Util.l(item.getComponent()+"\t\t"+item.getComponent()); //log
}
SAXXMLHandler look:
public class SAXXMLHandler extends DefaultHandler {
public static ArrayList<itemsList> items;
private itemsList item;
public SAXXMLHandler() {
items = new ArrayList<itemsList>();
}
public void characters(char[] ch, int start, int length)
throws SAXException {
}
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
item = new itemsList();
Log.d("INFO", "startElement " + localName + ", " + qName);
if (qName.equalsIgnoreCase("item")) {
item.setComponent(attributes.getValue("component"));
items.add(item);
}
}
public void endElement(String uri, String localName, String qName)
throws SAXException {
}
}
And still nothing :/
XML file in other app which I parse
http://pastebin.com/5GEthfmU
In the given XML line..
<item name="test" value="somedata" />
name and value are attributes which only can be retrieved in startElement() method. Because, Attributes attributes parameter is only passed into startElement(String uri, String localName, String qName, Attributes attributes) method. If you look at endElement(String uri, String localName, String qName) method there has no Attributes attributes. That's why you can't retrieve any attribute from endElement() method. So, if you want to retrieve any attributes from a XML then you have to retrieve them inside startElement(String uri, String localName, String qName, Attributes attributes) method.
Change System.out.println to ur Log.ins ..
Item .java
package com.rofl;
public class Item {
private String component;
private String drawable;
public String getComponent() {
return component;
}
public void setComponent(String component) {
this.component = component;
}
public String getDrawable() {
return drawable;
}
public void setDrawable(String drawable) {
this.drawable = drawable;
}
}
SAXXMLHandler .java
package com.rofl;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class SAXXMLHandler extends DefaultHandler {
public static void main(String argv[]) {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
SAXXMLHandler handler = new SAXXMLHandler();
saxParser.parse("src/file.xml", handler);
System.out.println(SAXXMLHandler.itemList.size());
for(Item item:itemList)
{
System.out.println(item.getComponent()+"\t\t"+item.getDrawable());
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static List<Item> itemList = new ArrayList<Item>();
private Item item;
public SAXXMLHandler() {
itemList = new ArrayList<Item>();
}
public void characters(char[] ch, int start, int length)
throws SAXException {
}
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
item = new Item();
if (qName.equalsIgnoreCase("item")) {
item.setComponent(attributes.getValue("component"));
item.setDrawable(attributes.getValue("drawable"));
itemList.add(item);
}
}
public void endElement(String uri, String localName, String qName)
throws SAXException {
}
}
output will be:-
8
ComponentInfo{com.designrifts.ultimatethemeui/ultimatethemeui.themeactivity} icon
ComponentInfo{com.chrislacy.actionlauncher.pro/com.chrislacy.launcher.Launcher} apps_actionlauncherpro
ComponentInfo{com.teslacoilsw.launcher/com.android.launcher2.Launcher} apps_novalauncher
ComponentInfo{com.teslacoilsw.launcher.prime/.NovaLauncherPrimeActivity} apps_novalauncher
ComponentInfo{com.anddoes.launcher/com.anddoes.launcher.Launcher} apps_apexlauncher
ComponentInfo{com.anddoes.launcher.pro/com.anddoes.launcher.pro.ApexLauncherProActivity} apps_apexlauncher
ComponentInfo{org.adw.launcher/org.adw.launcherlib.Launcher} apps_adwlauncher
ComponentInfo{org.adwfreak.launcher/org.adw.launcherlib.Launcher} apps_adwex
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());
}
}
}
i am trying to parse an xml file from an URL. I found an example in the following link
http://www.anddev.org/parsing_xml_from_the_net_-_using_the_saxparser-t353.html
and tried using it in my code but it returned the values to be as null
Following is my code of parsing xml
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
URL url = new URL("http://www.siva.com/search");
/** Handling XML */
SAXParserFactory saxparserfactory = SAXParserFactory.newInstance();
SAXParser saxparser = saxparserfactory.newSAXParser();
XMLReader xmlreader = saxparser.getXMLReader();
/* Create a new ContentHandler and apply it to the XML-Reader*/
ForListXMLHandler forlistmyhandler = new ForListXMLHandler();
xmlreader.setContentHandler(forlistmyhandler);
/* Parse the xml-data from our URL. */
xmlreader.parse(new InputSource(url.openStream()));
/* Parsing has finished. */
/* Our ExampleHandler now provides the parsed data to us. */
ParsedDataSet parsedDataSet = forlistmyhandler.getParsedData();
System.out.println(parsedDataSet.toString());
}
following is the code of MyXMLhandler
public class ForListXMLHandler extends DefaultHandler {
private boolean in_outertag = false;
private boolean in_innertag = false;
private boolean in_First_name = false;
private boolean in_Last_name = false;
private ParsedDataSet myParsedDataSet = new ParsedDataSet();
public ParsedDataSet getParsedData() {
return this.myParsedDataSet;
}
#Override
public void startDocument() throws SAXException {
this.myParsedDataSet = new ParsedDataSet();
}
#Override
public void endDocument() throws SAXException {
// Nothing to do
}
public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
if (localName.equals("Searchdata")) {
this.in_outertag = true;
} else if (localName.equals("Searchdata")) {
this.in_innertag = true;
} else if (localName.equals("First_name")) {
this.in_First_name = true;
} else if (localName.equals("Last_name")) {
this.in_Last_name = true;
}
}
/**
* Gets be called on closing tags like:
* */
#Override
public void endElement(String namespaceURI, String localName, String qName) throws SAXException {
if (localName.equals("Searchdata")) {
this.in_outertag = false;
} else if (localName.equals("Searchdata")) {
this.in_innertag = false;
} else if (localName.equals("First_name")) {
this.in_First_name = false;
} else if (localName.equals("Last_name")) {
// Nothing to do here
}
}
/**
* Gets be called on the following structure: characters
*/
#Override
public void characters(char ch[], int start, int length) {
if (this.in_First_name) {
myParsedDataSet.setfirstname(new String(ch, start, length));
}
if (this.in_Last_name) {
myParsedDataSet.setlastname(new String(ch, start, length));
}
}
}
next part is of my parsed data set class
public class ParsedDataSet {
private String First_name = null;
private String Last_name = null;
public String getFirstname() {
return First_name;
}
public void setfirstname(String First_name) {
this.First_name = First_name;
}
public String getlastname() {
return Last_name;
}
public void setlastname(String Last_name) {
this.Last_name = Last_name;
}
public String toString() {
return this.First_name + "n" + this.Last_name;
}
}
pls tell me where i am getting error
The endElement method gets fired before the characters method, so your boolean variables are always set to false when the characters method gets fired. You should move some code from endElement to characters, something like this:
#Override
public void endElement(String namespaceURI, String localName, String qName) throws SAXException {
}
#Override
public void characters(char ch[], int start, int length) {
if (this.in_First_name) {
this.in_First_name = false;
myParsedDataSet.setfirstname(new String(ch, start, length));
}
if (this.in_Last_name) {
this.in_Last_name = false;
myParsedDataSet.setlastname(new String(ch, start, length));
}
}
You should also take a look here for a complete explanation on "Working with XML on Android".
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.