XML SAXParser reformat if else Java/Android - java

I have the following problem:
I am using an XML SAXParser to parse an xml file and create dynamicly classes and set their properties.
I have written code that works now to make 4 classes and set the properiets of the classes but the problem is that the code is one big conditional case (if/else if/else) and that it is very difficult to read.
I would like to parse the xml so I can create 15 different classes, so the code is getting very big.
Now the exact question is how to refactor the if/elseif/else to better readable code? I've searched around for a while now and found some methods like using a map or the command pattern but I don't understand how to use this?
This is the code I'm currently using and that is working:
public class XmlParserSax extends DefaultHandler {
List<Fragment> fragments = null;
String atType = null;
String typeObject;
String currentelement = null;
String atColor = null;
RouteFragment route = null;
ChapterFragment chapter = null;
FirstFragment first = null;
ExecuteFragment execute = null;
StringBuilder textBuilder;
public XmlParserSax() {
fragments = new ArrayList<Fragment>();
try {
/**
* Create a new instance of the SAX parser
**/
SAXParserFactory saxPF = SAXParserFactory.newInstance();
SAXParser sp = saxPF.newSAXParser();
XMLReader xr = sp.getXMLReader();
/**
* Create the Handler to handle each of the XML tags.
**/
String file = "assets/test.xml";
InputStream in = this.getClass().getClassLoader()
.getResourceAsStream(file);
xr.setContentHandler(this);
xr.parse(new InputSource(in));
} catch (Exception e) {
System.out.println(e);
}
}
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
atColor = attributes.getValue("color");
atType = attributes.getValue("type");
currentelement = localName;
textBuilder = new StringBuilder();
if (localName.equalsIgnoreCase("template")) {
if (atType.equalsIgnoreCase("route")) {
route = new RouteFragment();
typeObject = "route";
} else if (atType.equalsIgnoreCase("chapter")) {
chapter = new ChapterFragment();
typeObject = "chapter";
} else if (atType.equalsIgnoreCase("first")) {
first = new FirstFragment();
typeObject = "first";
} else if (atType.equalsIgnoreCase("execute")) {
execute = new ExecuteFragment();
typeObject = "execute";
}
} else if (localName.equalsIgnoreCase("number")) {
if (typeObject.equalsIgnoreCase("chapter")) {
chapter.setNumberTextcolor("#" + atColor);
}
} else if (localName.equalsIgnoreCase("maxnumber")) {
if (typeObject.equalsIgnoreCase("chapter")) {
chapter.setMaxNumberColor("#" + atColor);
}
} else if (localName.equalsIgnoreCase("title")) {
if (typeObject.equalsIgnoreCase("chapter")) {
chapter.setTitleColor("#" + atColor);
} else if (typeObject.equalsIgnoreCase("first")) {
first.setTitleColor("#" + atColor);
}
} else if (localName.equalsIgnoreCase("subtitle")) {
if (typeObject.equalsIgnoreCase("first")) {
first.setSubtitleColor("#" + atColor);
}
} else if (localName.equalsIgnoreCase("text")) {
if (typeObject.equalsIgnoreCase("execute")) {
execute.setTextColor("#" + atColor);
}
}
}
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
String text = textBuilder.toString();
if (localName.equalsIgnoreCase("template")) {
if (typeObject.equalsIgnoreCase("route")) {
fragments.add(route); // nieuw routefragment
// toevoegen aan de lijst
} else if (typeObject.equalsIgnoreCase("chapter")) {
fragments.add(chapter); // nieuw chapterfragment
// toevoegen aan de lijst
} else if (typeObject.equalsIgnoreCase("first")) {
fragments.add(first);
} else if (typeObject.equalsIgnoreCase("execute")) {
fragments.add(execute);
}
} else if (localName.equalsIgnoreCase("text")) {
if (typeObject.equalsIgnoreCase("route")) {
// route.setOmschrijving(text);
} else if (typeObject.equalsIgnoreCase("execute")) {
execute.setText(text);
}
} else if (localName.equalsIgnoreCase("background")) {
if (typeObject.equalsIgnoreCase("route")) {
// route.setKleur("#" + text);
} else if (typeObject.equalsIgnoreCase("chapter")) {
chapter.setBackgroundColor("#" + text);
} else if (typeObject.equalsIgnoreCase("first")) {
first.setBackgroundColor("#" + text);
} else if (typeObject.equalsIgnoreCase("execute")) {
execute.setBackgroundColor("#" + text);
}
} else if (localName.equalsIgnoreCase("number")) {
if (typeObject.equalsIgnoreCase("chapter")) {
chapter.setNumber(text);
}
} else if (localName.equalsIgnoreCase("maxnumber")) {
if (typeObject.equalsIgnoreCase("chapter")) {
chapter.setMaxNumber(text);
}
} else if (localName.equalsIgnoreCase("title")) {
if (typeObject.equalsIgnoreCase("chapter")) {
chapter.setTitle(text);
} else if (typeObject.equalsIgnoreCase("first")) {
first.setTitle(text);
}
} else if (localName.equalsIgnoreCase("subtitle")) {
if (typeObject.equalsIgnoreCase("first")) {
first.setSubtitle(text);
}
} else if (localName.equalsIgnoreCase("square")) {
if (typeObject.equalsIgnoreCase("execute")) {
execute.setBorderColor("#" + text);
}
}
}
public List<Fragment> getList() {
return fragments;
}
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
textBuilder.append(ch, start, length);
}
}

There is another way of doing this; using startElementListener and EndTextElementListeners
First define your root element:
RootElement root = new RootElement("root");
Define your child elements
Element nodeA = root.getChild("nodeA");
Element nodeB = root.getChild("nodeB");
Element nodeC = root.getChild("nodeC");
Now set the listeners
root.setStartElementListener(new StartElementListener() {
public void start(Attributes attributes) {
foundElement = true;// tells you that you are parsing the intended xml
}
});
nodeA.setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
//populate your pojo
}
});
This way you can do away with all those if-else statements and booleans, but you have to live with the N number of listeners.

Related

Issue while fetching Imagesg from RSS feed

I'm trying to get the RSS feed into my android application, I am retrieving feeds like title, description and link of feed but not able to get image for particular feed.
The fallowing is my DefaultXmlHandler class. please go through and help me out.
public class XmlHandler extends DefaultHandler {
private RssFeedStructure feedStr = new RssFeedStructure();
private List<RssFeedStructure> rssList = new ArrayList<RssFeedStructure>();
private int articlesAdded = 0;
// Number of articles to download
private static final int ARTICLES_LIMIT = 15;
StringBuffer chars = new StringBuffer();
public void startElement(String uri, String localName, String qName, Attributes atts) {
chars = new StringBuffer();
if (qName.equalsIgnoreCase("media:content"))
{
if(!atts.getValue("url").toString().equalsIgnoreCase("null")){
feedStr.setImgLink(atts.getValue("url").toString());
}
else{
feedStr.setImgLink("");
}
}
}
public void endElement(String uri, String localName, String qName) throws SAXException {
if (localName.equalsIgnoreCase("title"))
{
feedStr.setTitle(chars.toString());
}
else if (localName.equalsIgnoreCase("description"))
{
feedStr.setDescription(chars.toString());
}
else if (localName.equalsIgnoreCase("pubDate"))
{
feedStr.setPubDate(chars.toString());
}
else if (localName.equalsIgnoreCase("encoded"))
{
feedStr.setEncodedContent(chars.toString());
}
else if (qName.equalsIgnoreCase("media:content"))
{
}
else if (localName.equalsIgnoreCase("link"))
{
try {
feedStr.setUrl(new URL(chars.toString()));
}catch (Exception e){}
}
if (localName.equalsIgnoreCase("item")) {
rssList.add(feedStr);
feedStr = new RssFeedStructure();
articlesAdded++;
if (articlesAdded >= ARTICLES_LIMIT)
{
throw new SAXException();
}
}
}
public void characters(char ch[], int start, int length) {
chars.append(new String(ch, start, length));
}
public List<RssFeedStructure> getLatestArticles(String feedUrl) {
URL url = null;
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
url = new URL(feedUrl);
xr.setContentHandler(this);
xr.parse(new InputSource(url.openStream()));
} catch (IOException e) {
} catch (SAXException e) {
} catch (ParserConfigurationException e) {
}
return rssList;
}
}

How to bind data in java?

I will read the data from an xml file and list the properties of the elements in a page.
With my code you can already read the data and store them in a list. But unfortunately, data binding does not work. Please help ..
bookHandler
public class bookHandler implements ContentHandler {
private String currentValue;
boolean tablecaption;
private boolean bookObjectCreated = false;
private boolean inbookSection = false;
bookObject currentbookObject;
private boolean inbody = false;
private boolean namebook = false;
private boolean authbook = false;
private List<bookObject> booksList = null;
public List<bookObject> getbookList() {
return booksList;
}
public void characters(char[] ch, int start, int length) throws SAXException {
currentValue = new String(ch, start, length);
}
public void startElement(String uri, String localName, String qname, Attributes atts) throws SAXException {
if ((localName.equals("TABLE-PRE")) && (atts.getValue("ID").equals("action"))) {
inbookSection = true;
}
if (inbookSection) {
if (localName.equals("BODY")) {
inbody = true;
}
}
if (inbody) {
if (localName.equals("ROW")) {
bookObjectCreated = true;
currentbookObject = new bookObject();
if (booksList == null)
booksList = new ArrayList<bookObject>();
}
if (bookObjectCreated) {
if (localName.equals("ENTRY") && (atts.getValue("COLNAME").equals("col1"))) {
namebook = true;
} else if (localName.equals("ENTRY") && (atts.getValue("COLNAME").equals("col2"))) {
authbook = true;
}
}
}
}
public void endElement(String uri, String localName, String atts) throws SAXException {
if (bookObjectCreated) {
if (namebook) {
if (atts.equals("P")) {
currentbookObject.setName(currentValue);
namebook = false;
}
}
else if (authbook) {
if (atts.equals("P")) {
currentbookObject.setAuth(currentValue);
authbook = false;
}
}
if (atts.equals("ROW")) {
bookObjectCreated = false;
booksList.add(currentbookObject);
authbook = false;
}
}
if (atts.equals("BODY")) {
inbody = false;
inbookSection = false;
}
}
bookObject.java
public class bookObject {
private String name;
private String Auth;
public bookObject() {
}
public String getName() {
return name;
}
public String getAuth() {
return Auth;
}
public void setName(String name) {
this.name = name;
}
public void setAuth(String status) {
this.Auth = status;
}
}
Main.java
public class Main {
private String m_InputPath = "bspXml.xml";
public void createBooks() {
// m_ResultGroups = new ResultGroups();
try {
XMLReader xmlReader = XMLReaderFactory.createXMLReader();
FileReader reader = new FileReader(m_InputPath);
InputSource inputSource = new InputSource(reader);
xmlReader.setContentHandler(new bookHandler());
xmlReader.parse(inputSource);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
}
}
Wizard
public Wizard(App app) {
super("wizardPage");
//books
App.createBooks();
}
public void createControl(Composite parent) {
Composite container = new Composite(parent, SWT.NULL);
setControl(container);
container.setLayout(new BorderLayout(0, 0));
checkboxTableViewer = CheckboxTableViewer.newCheckList(container, SWT.BORDER | SWT.FULL_SELECTION);
checkboxTableViewer.setAllGrayed(true);
checkboxTableViewer.setAllChecked(false);
table = checkboxTableViewer.getTable();
table.setHeaderVisible(true);
table.setLayoutData(BorderLayout.CENTER);
tableViewerColumn = new TableViewerColumn(checkboxTableViewer, SWT.NONE);
tblclmnName = tableViewerColumn.getColumn();
tblclmnName.setWidth(255);
tblclmnName.setText("Name");
tableViewerColumn_1 = new TableViewerColumn(checkboxTableViewer, SWT.NONE);
tblclmnVariant = tableViewerColumn_1.getColumn();
tblclmnVariant.setWidth(122);
tblclmnVariant.setText("Author");
m_bindingContext = iDataBindings();
}
protected DataBindingContext iDataBindings() {
DataBindingContext bindingContext = new DataBindingContext();
//
IObservableValue observeTextTblclmnNameObserveWidget = WidgetProperties.text().observe(tblclmnName);
IObservableValue namebookObjectObserveValue = PojoProperties.value("name").observe(bookObject);
bindingContext.bindValue(observeTextTblclmnNameObserveWidget, namebookObjectObserveValue, null, null);
//
IObservableValue observeTextTblclmnVariantObserveWidget = WidgetProperties.text().observe(tblclmnVariant);
IObservableValue statusbookObjectObserveValue = PojoProperties.value("author").observe(bookObject);
bindingContext.bindValue(observeTextTblclmnVariantObserveWidget, statusbookObjectObserveValue, null, null);
//
return bindingContext;
}
}
xml
<?xml version="1.0" encoding="iso-8859-1" ?>
<BOOK>
<TABLE>
<TABLE-PRE ID="sinceBook">
<NAME>sinceBook</NAME>
</TABLE-PRE>
</TABLE>
<TABLE>
<TABLE-PRE ID="actionBook">
<NAME>actionBook</NAME>
</TABLE-PRE>
<TABLEGR COLS="2">
<COLSPE COLNUM="1" COLWIDTH="4.31*" COLNAME="col1"/>
<COLSPE COLNUM="2" COLWIDTH="1.00*" COLNAME="col2"/>
<TD>
<ROW>
<ENTRY COLNAME="col1">
<P>Name</P>
</ENTRY>
<ENTRY COLNAME="col2">
<P>Author</P>
</ENTRY>
</ROW>
</TD>
<BODY>
<ROW>
<ENTRY COLNAME="col1">
<P>Harry Potter </P>
</ENTRY>
<ENTRY COLNAME="col2">
<P>Joanne K. Rowling</P>
Even without reading your code carefully I would like to mention that you are working too hard to achieve what you need. Use JAXB to map XML schema to java class. Learn the basics during 15 minutes, put appropriate annotations on your model classes, write 3-4 lines of code and you are done.
EDIT
Take a look on this tutorial first: http://www.vogella.com/tutorials/JAXB/article.html
Or alternatively search for any other JAXB tutorial on web.

ADF Faces: It's possible to Customize Error Handling without ADF BC

Is there away to customize Error Handling in ADF Faces without ADF BC?
This is my approach.
Class MyErrorHandler extends DCErrorHandlerImpl
public class MyErrorHandler extends DCErrorHandlerImpl {
private static final ADFLogger logger = ADFLogger.createADFLogger(MyErrorHandler.class);
private static ResourceBundle rb =
ResourceBundle.getBundle("error.handling.messages.ErrorMessages_de_DE");
public MyErrorHandler() {
super(true);
}
public MyErrorHandler(boolean setToThrow) {
super(setToThrow);
}
public void reportException(DCBindingContainer bc, java.lang.Exception ex) {
disableAppendCodes(ex);
logger.info("entering reportException() method");
BindingContext ctx = bc.getBindingContext();
if (ex instanceof NullPointerException) {
logger.severe(ex);
JboException e = new JboException(rb.getString("STANDARD_ERROR_MESSAGE"));
super.reportException(bc, e);
} else if (ex instanceof RowValException) {
Object[] exceptions = ((RowValException) ex).getDetails();
if (exceptions != null) {
for (int i = 0; i < exceptions.length; i++) {
if (exceptions[i] instanceof RowValException) {
this.reportException(bc, (Exception) exceptions[i]);
} else if (exceptions[i] instanceof AttrValException) {
super.reportException(bc, (Exception) exceptions[i]);
}
}
} else {
this.reportException(bc, ex);
}
} else if (ex instanceof TxnValException) {
Object[] exceptions = ((TxnValException) ex).getDetails();
if (exceptions != null) {
for (int i = 0; i < exceptions.length; i++) {
if (exceptions[i] instanceof RowValException) {
this.reportException(bc, (Exception) exceptions[i]);
} else {
super.reportException(bc, (Exception) exceptions[i]);
}
}
} else {
super.reportException(bc, ex);
}
}
else if (ex instanceof oracle.jbo.DMLException) {
JboException e = new JboException(rb.getString("STANDARD_ERROR_MESSAGE"));
super.reportException(bc, e);
} else if (ex instanceof javax.xml.ws.WebServiceException) {
JboException e = new JboException(rb.getString("WEB_SERVICE_EXCEPTION"));
super.reportException(bc, e);
}
else if (ex instanceof JboException) {
super.reportException(bc, ex);
}
}
public static FacesMessage getMessageFromBundle(String key, FacesMessage.Severity severity) {
ResourceBundle bundle =
ResourceBundle.getBundle("sahaj.apps.vleadministration.view.resources.VLEAdministrationUIBundle");
String summary = JSFUtils.getStringSafely(bundle, key, null);
String detail = JSFUtils.getStringSafely(bundle, key + "_detail", summary);
FacesMessage message = new FacesMessage(summary, detail);
message.setSeverity(severity);
return message;
}
private void disableAppendCodes(Exception ex) {
if (ex instanceof JboException) {
JboException jboEx = (JboException) ex;
jboEx.setAppendCodes(false);
Object[] detailExceptions = jboEx.getDetails();
if ((detailExceptions != null) && (detailExceptions.length > 0)) {
for (int z = 0, numEx = detailExceptions.length; z < numEx; z++) {
System.err.println("Detailed Exception : "+ detailExceptions[z].toString());
disableAppendCodes((Exception) detailExceptions[z]);
}
}
}
}
#Override
protected boolean skipException(Exception ex) {
if (ex instanceof JboException) {
return false;
} else if (ex instanceof SQLIntegrityConstraintViolationException) {
return true;
}
return super.skipException(ex);
}
private String handleApplicationError(String errorMessageRaw) {
String errorMessageCode = getErrorCode(errorMessageRaw);
// application error code
String errorMessage = null;
for (String key : errorPrefixes) {
if (errorMessageCode.startsWith(key)) {
try {
errorMessage = rb.getString(errorMessageCode);
} catch (MissingResourceException mre) {
// application error code not found in the bundle,
// use original message
return errorMessageRaw;
}
break;
}
}
// return the formated application error message
return errorMessage;
}
private String getErrorCode(String errorMessageRaw) {
// check for null/empty error message
if (errorMessageRaw == null || errorMessageRaw.isEmpty()) {
return errorMessageRaw;
}
int start = 0;
String currentErrorCodePrefix = null;
int count = 0;
// check for error message
for (String errorCode : errorPrefixes) {
count += 1;
start = errorMessageRaw.indexOf(errorCode);
if (start >= 0) {
currentErrorCodePrefix = errorCode;
start += currentErrorCodePrefix.length();
break;
}
if (count == errorPrefixes.size())
return errorMessageRaw;
}
int endIndex = start + 5;
// get the CURRENT error code
return currentErrorCodePrefix + errorMessageRaw.substring(start, endIndex);
}
#Override
public String getDisplayMessage(BindingContext bindingContext, Exception exception) {
String data=super.getDisplayMessage(bindingContext, exception);
System.err.println("Exception DATA : "+ data);
String msg= handleApplicationError(data);
System.err.println("Exception MSG : "+ msg);
return msg;
}
#Override
public DCErrorMessage getDetailedDisplayMessage(BindingContext bindingContext, RegionBinding regionBinding,
Exception exception) {
return super.getDetailedDisplayMessage(bindingContext, regionBinding, exception);
}
private static Set<String> errorPrefixes = new HashSet<String>();
static {
errorPrefixes.add("JBO-");
errorPrefixes.add("ORA-");
errorPrefixes.add("DCA-");
}
}
In my DataBinding.cpx
<Application xmlns="http://xmlns.oracle.com/adfm/application" version="12.1.2.66.68" id="DataBindings"
SeparateXMLFiles="false" Package="de.nkk.oasis.ui.web" ClientType="Generic"
ErrorHandlerClass="MyErrorHandler">
After that i generate Data Controller from Myclass.
//MyClass
/**
* method throwing a Nullpointer exception
*/
public void throwNPE() {
Object o = null;
String s = o.toString();
//bang occurs in the line above, no need for any more code
//...
}
/**
* Method that throws a single JboException
*/
public void throwJboException(){
throw new JboException("This is a JboException thrown in ADF BC");
}
and bind the two methods to JSF
<af:button actionListener="#{bindings.throwNPE.execute}" text="throwNPE"
disabled="#{!bindings.throwNPE.enabled}" id="b2"/>
<af:button actionListener="#{bindings.throwJboException.execute}" text="throwJboException"
disabled="#{!bindings.throwJboException.enabled}" id="b3"/>
NOW COMES MY PROBLEM:
Whenever i click one the Button i get
DCA-29000 unexcepted Exception
Try remove
disabled="#{!bindings.throwNPE.enabled}"
and
disabled="#{!bindings.throwJboException.enabled}"

Android sax parser error while getting html data

Hi Am trying to parse the data from xml which contains the html data using sax parser the data in xml is like below
but while parsing am getting the data between details tag as different strings, not getting as single string which contains full html data between dtails tag.
can anyone help me out please how can i resolve this.
<details>
<html> <b>Animal Care BTEC Level 1</b>
<hr style="height:0.03em;width:18em;border:1px ;border-style:dotted;margin-left:0; color:white"
/>
<body>
<e>Course Length: 1 year</e>
<br />
<e>Fees: Free for 16-18 year olds</e>
<br />
<e>Course Code: B332</e>
<br />
<br />
<body> <b> Overview:</b>
<hr style="height:0.03em;width:18em;border:1px ;border-style:dotted;margin-left:0 ;color:white"
/>
<p>The course provides a basic introduction to working with animals. A practical
approach allows student to develop animal handling skills along side personal
and social development. Student will have access to a wide range of animals
to enable them to develop skills and confidence. Each week practical work
will include time spent on the animal unit, the farm and at the equine
centre to enable students to develop practical ability in all three areas.</p>
</body>
</html>
</details>
package com.bb.mypotential;
import java.util.ArrayList;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import android.util.Log;
public class SaxHandler extends DefaultHandler {
public static Courseobj courseobj;
public static Subject subjectobj;
public boolean courseidb = false;
public boolean coursesubjectb = false;
public boolean coursetitleb = false;
public boolean subjectidb = false;
public boolean subjectnameb = false;
public boolean subjectcodeb = false;
public boolean subjectdetailsb = false;
public boolean entryRequirementb = false;
public boolean courseContentb = false;
public boolean futhuroptionsb = false;
public boolean additionalInfob = false;
public boolean fundingInfob = false;
public boolean assignmethodb = false;
public String currentvalue = null;
public ArrayList<Subject> subarr = null;
String TAG = getClass().getSimpleName();
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// TODO Auto-generated method stub
if (localName.equals("Courses")) {
MainListActivity.value = new ArrayList<Courseobj>();
}
if (localName.equals("Course")) {
courseobj = new Courseobj();
subarr = new ArrayList<Subject>();
String courseid = attributes.getValue(0);// getValue("ID");
courseobj.setCOURSE_ID(courseid);
courseidb = true;
} else if (localName.equalsIgnoreCase("title")) {
coursetitleb = true;
} else if (localName.equals("subject")) {
subjectobj = new Subject();
String subid = attributes.getValue(0);
subjectobj.setSUB_ID(subid);
subjectidb = true;
} else if (localName.equals("name")) {
subjectnameb = true;
} else if (localName.equals("code")) {
subjectcodeb = true;
} else if (localName.equals("details")) {
subjectdetailsb = true;
} else if (localName.equals("entryRequirement")) {
entryRequirementb = true;
} else if (localName.equals("courseContent")) {
courseContentb = true;
} else if (localName.equals("assignmentMethods")) {
assignmethodb = true;
} else if (localName.equals("furtherOptions")) {
futhuroptionsb = true;
} else if (localName.equals("additionalInformation")) {
additionalInfob = true;
} else if (localName.equals("fundingInformation")) {
fundingInfob = true;
}
}
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
// TODO Auto-generated method stub
currentvalue = new String(ch, start, length);
if (coursetitleb) {
courseobj.setTitle(currentvalue);
} else if (subjectnameb) {
subjectobj.setName(currentvalue);
} else if (subjectcodeb) {
subjectobj.setCode(currentvalue);
} else if (subjectdetailsb) {
subjectobj.setDetails(currentvalue);
} else if (entryRequirementb) {
subjectobj.setEntryRequirement(currentvalue);
} else if (courseContentb) {
subjectobj.setCourseContent(currentvalue);
} else if (assignmethodb) {
subjectobj.setCourseContent(currentvalue);
} else if (futhuroptionsb) {
subjectobj.setFuthuroptions(currentvalue);
} else if (additionalInfob) {
subjectobj.setAdditionalInfo(currentvalue);
} else if (fundingInfob) {
subjectobj.setFundingInfo(currentvalue);
}
}
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
// TODO Auto-generated method stub
if (localName.equalsIgnoreCase("Course")) {
courseobj.setSubject(subarr);
MainListActivity.value.add(courseobj);
courseidb = false;
} else if (localName.equalsIgnoreCase("title")) {
coursetitleb = false;
} else if (localName.equals("subject")) {
subarr.add(subjectobj);
subjectidb = false;
} else if (localName.equals("name")) {
subjectnameb = false;
} else if (localName.equals("code")) {
subjectcodeb = false;
} else if (localName.equals("details")) {
subjectdetailsb = false;
} else if (localName.equals("entryRequirement")) {
entryRequirementb = false;
} else if (localName.equals("courseContent")) {
courseContentb = false;
} else if (localName.equals("assignmentMethods")) {
assignmethodb = false;
} else if (localName.equals("furtherOptions")) {
futhuroptionsb = false;
} else if (localName.equals("additionalInformation")) {
additionalInfob = false;
} else if (localName.equals("fundingInformation")) {
fundingInfob = false;
}
}
}

Java Android : XML Parsing getting the value of a tag

I'm trying to parse an xml file but seem not to understand how it works. I have been debugging for hours but cant seem to get the correct value. I have managed to get the code working for the tracklist tag, but not for the playbacklist tag and his children tags.
I'm would like to have the values of a playback device, in the future more will be added.
this is the xml source:
<?xml version="1.0" encoding="ISO-8859-1"?>
<root>
<tracklist>
<track>track001.mp3</track>
<track>track002.mp3</track>
<track>track003.mp3</track>
<track>track004.mp3</track>
<track>track005.mp3</track>
<track>track006.mp3</track>
<track>track007.mp3</track>
<track>track008.mp3</track>
<track>track009.mp3</track>
<track>track010.mp3</track>
</tracklist>
<playbacklist>
<playback>
<name>Speaker1</name>
<ip>192.168.1.103</ip>
<room>Kitchen</room>
<options>0</options>
<state>NotPlaying</state>
</playback>
</playbacklist>
</root>
this is the java code (snippets of the code): this code is working for me
DocumentBuilder db = factory.newDocumentBuilder();
Document doc = db.parse(inStream);
NodeList nodeList = doc.getElementsByTagName("root");
for (int index = 0; index < nodeList.getLength(); index++) {
Node node = nodeList.item(index);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
NodeList nameNode = element.getChildNodes();
for (int iIndex = 0; iIndex < nameNode.getLength(); iIndex++) {
if (nameNode.item(iIndex).getNodeType() == Node.ELEMENT_NODE) {
Element nameElement = (Element) nameNode.item(iIndex);
if(nameElement.getNodeName().equals("tracklist")){
NodeList trackNodes = nameElement.getChildNodes();
for(int i=0;i<trackNodes.getLength();i++){
if (trackNodes.item(i).getNodeType() == Node.ELEMENT_NODE) {
Element trackElement = (Element) trackNodes.item(i);
playlist.add(trackElement.getFirstChild().getNodeValue());
}
}
}
this code isn't working for me:
if(nameElement.getNodeName().equals("playbacklist")){
NodeList devicesNodes = nameElement.getChildNodes();
for(int j=0;j<=devicesNodes.getLength();j++){
Node nodeDevice = devicesNodes.item(j);
NodeList childNodes = nodeDevice.getChildNodes();
I will suggest you to use SAX parser, it is easy and much efficient than others
how to parse : How to parse XML using the SAX parser
Here is your SaxParser generated by my Sax Class Generator
package sherif.java.sax;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class YourHandler extends DefaultHandler
{
//TAGS /\Sherif/\
private boolean root = false;
private boolean playbacklist = false;
private boolean playback = false;
private boolean name = false;
private boolean ip = false;
private boolean room = false;
private boolean options = false;
private boolean state = false;
private boolean tracklist = false;
private boolean track = false;
public YourHandler()
{
//TODO /\Sherif/\
}
#Override
public void startDocument() throws SAXException
{
super.startDocument();
//TODO /\Sherif/\
}
#Override
public void endDocument() throws SAXException
{
super.endDocument();
//TODO /\Sherif/\
}
#Override
public void characters(char sherifCh[], int sherifSt, int sherifle)
{
String value = (new String(sherifCh)).substring(sherifSt, sherifSt + sherifle);
if(root)
{
if(playbacklist)
{
if(playback)
{
if(name)
{
//TODO /\Sherif/\
}
else if(ip)
{
//TODO /\Sherif/\
}
else if(room)
{
//TODO /\Sherif/\
}
else if(options)
{
//TODO /\Sherif/\
}
else if(state)
{
//TODO /\Sherif/\
}
}
}
else if(tracklist)
{
if(track)
{
//TODO /\Sherif/\
}
}
}
}
#Override
public void startElement(String sherifUr, String sherifNa, String sherifQn, org.xml.sax.Attributes sherifAt) throws SAXException
{
super.startElement(sherifUr, sherifNa, sherifQn, sherifAt);
if(sherifNa.equals("root"))
{
this.root = true;
}
else if(sherifNa.equals("playbacklist"))
{
this.playbacklist = true;
}
else if(sherifNa.equals("playback"))
{
this.playback = true;
}
else if(sherifNa.equals("name"))
{
this.name = true;
}
else if(sherifNa.equals("ip"))
{
this.ip = true;
}
else if(sherifNa.equals("room"))
{
this.room = true;
}
else if(sherifNa.equals("options"))
{
this.options = true;
}
else if(sherifNa.equals("state"))
{
this.state = true;
}
else if(sherifNa.equals("tracklist"))
{
this.tracklist = true;
}
else if(sherifNa.equals("track"))
{
this.track = true;
}
}
#Override
public void endElement(String sherifUr, String sherifNa, String sherifQn) throws SAXException
{
super.endElement(sherifUr, sherifNa, sherifQn);
if(sherifNa.equals("root"))
{
this.root = false;
}
else if(sherifNa.equals("playbacklist"))
{
this.playbacklist = false;
}
else if(sherifNa.equals("playback"))
{
this.playback = false;
}
else if(sherifNa.equals("name"))
{
this.name = false;
}
else if(sherifNa.equals("ip"))
{
this.ip = false;
}
else if(sherifNa.equals("room"))
{
this.room = false;
}
else if(sherifNa.equals("options"))
{
this.options = false;
}
else if(sherifNa.equals("state"))
{
this.state = false;
}
else if(sherifNa.equals("tracklist"))
{
this.tracklist = false;
}
else if(sherifNa.equals("track"))
{
this.track = false;
}
}
}
You can use it:
String yourXmlString;
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
/* Create a new instance of the class generated */
YourHandler handler = new YourHandler ();
xr.setContentHandler(handler);
InputSource inputSource = new InputSource();
inputSource.setEncoding("UTF-8");
inputSource.setCharacterStream(new StringReader(response));
/* Start Parsing */
xr.parse(inputSource);
/* Parsing Done. */

Categories

Resources