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.
Related
Previously, I was able to display the data of one tag, but this time not several values are displayed, but only one.
This my parser code:
public class Runner {
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser saxParser = spf.newSAXParser();
XMLReader xmlReader = saxParser.getXMLReader();
MyHandler handler = new MyHandler();
xmlReader.setContentHandler(handler);
xmlReader.parse("src/countries.xml");
Countries branches = handler.getBranches();
try (FileWriter files = new FileWriter("src/diploma/SAX.txt")) {
files.write("Item " + "\n" + String.valueOf(branches.itemList) + "\n");
}
}
private static class MyHandler extends DefaultHandler{
static final String HISTORY_TAG = "history";
static final String ITEM_TAG = "item";
static final String NAME_ATTRIBUTE = "name";
public Countries branches;
public Item currentItem;
private String currencyElement;
Countries getBranches(){
return branches;
}
public void startDocument() throws SAXException {
}
#Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
currencyElement = qName;
switch (currencyElement) {
case HISTORY_TAG: {
branches.itemList = new ArrayList<>();
currentItem = new Item();
currentItem.setHistoryName(String.valueOf(attributes.getValue(NAME_ATTRIBUTE)));
} break;
default: {}
}
}
#Override
public void characters(char[] ch, int start, int length) throws SAXException {
String text = new String(ch, start, length);
if (text.contains("<") || currencyElement == null){
return;
}
switch (currencyElement) {
case ITEM_TAG: {
currentItem.setItem(text);
} break;
default: { }
}
}
#Override
public void endElement(String uri, String localName, String qName) throws SAXException{
switch (qName) {
case HISTORY_TAG: {
branches.itemList.add(currentItem);
currentItem = null;
} break;
default: {
}
}
currencyElement = null;
}
public void endDocument() throws SAXException {
System.out.println("SAX parsing is completed...");
}
}
}
Class Item:
public class Item {
private String historyName;
private String item;
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
public String getHistoryName() {
return historyName;
}
public void setHistoryName(String historyName) {
this.historyName = historyName;
}
#Override
public String toString() {
return
"historyName = " + historyName + ", " + "\n" + "item = " + item + ", ";
}
}
And class Countries
public class Countries {
public List<Item> itemList;
}
I have problems with this part
<history name="История">
<item>
История белорусских земель очень богата и самобытна.
</item>
<item>
Эту страну постоянно раздирали внутренние конфликты и противоречия, много раз она была втянута в войны.
</item>
<item>
В 1945 году Беларусь вступила в состав членов-основателей Организации Объединенных Наций.
</item>
</history>
I only display the last "item" tag, and other duplicate tags are displayed only in the singular. I can't figure out where the error is, but I noticed that in "endElement" all values are displayed, but as one element. Maybe someone knows what's the matter?
You are creating a new ArrayList every time you encounter the item tag.
That is why you only see one item displayed after parsing.
Here, I'm using SAX method for parsing array. I'm facing an issue where I'm not able to write a generic code to parse an array type of xml. I couldn't find a solution for generic way methodology to identify it as an array and iterate over it and store it in List
<bookstore>
<book category="children">
<title>Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="web">
<title>Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
Any solution will help. Thanks in advance
I use code below. I got it from: https://github.com/niteshapte/generic-xml-parser
public class GenericXMLParserSAX extends DefaultHandler {
private ListMultimap<String, String> listMultimap = ArrayListMultimap.create();
String tempCharacter;
private String[] startElements;
private String[] endElements;
public void setStartElements(String[] startElements) {
this.startElements = startElements;
}
public String[] getStartElements() {
return startElements;
}
public void setEndElements(String[] endElements) {
this.endElements = endElements;
}
public String[] getEndElements() {
return endElements;
}
public void parseDocument(String xml, String[] startElements, String[] endElements) {
setStartElements(startElements);
setEndElements(endElements);
SAXParserFactory spf = SAXParserFactory.newInstance();
try {
SAXParser sp = spf.newSAXParser();
InputStream inputStream = new ByteArrayInputStream(xml.getBytes());
sp.parse(inputStream, this);
} catch(SAXException se) {
se.printStackTrace();
} catch(ParserConfigurationException pce) {
pce.printStackTrace();
} catch (IOException ie) {
ie.printStackTrace();
}
}
public void parseDocument(String xml, String[] endElements) {
setEndElements(endElements);
SAXParserFactory spf = SAXParserFactory.newInstance();
try {
SAXParser sp = spf.newSAXParser();
InputStream inputStream = new ByteArrayInputStream(xml.getBytes());
sp.parse(inputStream, this);
} catch(SAXException se) {
se.printStackTrace();
} catch(ParserConfigurationException pce) {
pce.printStackTrace();
} catch (IOException ie) {
ie.printStackTrace();
}
}
#Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
String[] startElements = getStartElements();
if(startElements!= null){
for(int i = 0; i < startElements.length; i++) {
if(qName.startsWith(startElements[i])) {
listMultimap.put(startElements[i], qName);
}
}
}
}
#Override
public void characters(char[] ch, int start, int length) throws SAXException {
tempCharacter = new String(ch, start, length);
}
#Override
public void endElement(String uri, String localName, String qName) throws SAXException {
String[] endElements = getEndElements();
for(int i = 0; i < endElements.length; i++) {
if (qName.equalsIgnoreCase(endElements[i])) {
listMultimap.put(endElements[i], tempCharacter);
}
}
}
public ListMultimap<String, String> multiSetResult() {
return listMultimap;
}
}
You can create a custom Handler that extends DefaultHandler and use it to parse your XML and generate the List<Book> for you.
The Handler will maintain a List<Book> and:
every time it will encounter the book start tag, it will create a new Book
every time it will encounter the book end tag, it will add this Book to the List.
In the end it will be holding the complete list of Books and you can access it via its getBooks() method
Assuming this Book class:
class Book {
private String category;
private String title;
private String author;
private String year;
private String price;
// GETTERS/SETTERS
}
You can create a custom Handler like this:
class MyHandler extends DefaultHandler {
private boolean title = false;
private boolean author = false;
private boolean year = false;
private boolean price = false;
// Holds the list of Books
private List<Book> books = new ArrayList<>();
// Holds the Book we are currently parsing
private Book book;
public void startElement(String uri, String localName,String qName, Attributes attributes) {
switch (qName) {
// Create a new Book when finding the start book tag
case "book": {
book = new Book();
book.setCategory(attributes.getValue("category"));
}
case "title": title = true;
case "author": author = true;
case "year": year = true;
case "price": price = true;
}
}
public void endElement(String uri, String localName, String qName) {
// Add the current Book to the list when finding the end book tag
if("book".equals(qName)) {
books.add(book);
}
}
public void characters(char[] ch, int start, int length) {
String value = new String(ch, start, length);
if (title) {
book.setTitle(value);
title = false;
} else if (author) {
book.setAuthor(value);
author = false;
} else if (year) {
book.setYear(value);
year = false;
} else if (price) {
book.setPrice(value);
price = false;
}
}
public List<Book> getBooks() {
return books;
}
}
Then you parse using this custom Handler and retrieve the list of Books
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
MyHandler myHandler = new MyHandler();
saxParser.parse("/path/to/file.xml", myHandler);
List<Book> books = myHandler.getBooks();
I have a simple Spring application (front-end application) that loads files into the Alfresco repository. If the file already exists, its new version is not created.
Repository web script is presented below:
public class CustomFileUploader extends DeclarativeWebScript {
private static final String FIRM_DOC =
"{http://www.firm.com/model/content/1.0}someDoc";
private static final String FIRM_DOC_FOLDER =
"workspace://SpacesStore/8caf07c3-6aa9-4a41-bd63-404cb3e3ef0f";
private FirmFile firmFile;
private FileFolderService fileFolderService;
private ContentService contentService;
protected Map<String, Object> executeImpl(WebScriptRequest req,
Status status) {
retrievePostRequestParams(req);
writeContent();
return null;
}
private void retrievePostRequestParams(WebScriptRequest req) {
FormData formData = (FormData) req.parseContent();
FormData.FormField[] fields = formData.getFields();
for(FormData.FormField field : fields) {
String fieldName = field.getName();
String fieldValue = field.getValue();
if(fieldName.equalsIgnoreCase("firm_file")
&& field.getIsFile()) {
String fileName = field.getFilename();
Content fileContent = field.getContent();
String fileMimetype = field.getMimetype();
firmFile = new FirmFile(fileName, fileContent,
fileMimetype, FIRM_DOC);
}
}
}
private void writeContent() {
try {
NodeRef parentNodeRef = new NodeRef(FIRM_DOC_FOLDER);
NodeRef fileNodeRef = createFileNode(parentNodeRef,
firmFile.getFileName());
ContentWriter contentWriter = contentService.getWriter(fileNodeRef,
ContentModel.PROP_CONTENT, true);
contentWriter.setMimetype(firmFile.getFileMimetype());
contentWriter.putContent(firmFile.getFileContent().getInputStream());
} catch (Exception e) {
e.printStackTrace();
}
}
private NodeRef createFileNode(NodeRef parentNode, String fileName) {
try {
QName contentQName = QName.createQName(FIRM_DOC);
FileInfo fileInfo = fileFolderService.create(parentNode,
fileName, contentQName);
return fileInfo.getNodeRef();
} catch (Exception e) {
e.printStackTrace();
}
}
public FileFolderService getFileFolderService() {
return fileFolderService;
}
public void setFileFolderService(FileFolderService fileFolderService) {
this.fileFolderService = fileFolderService;
}
public ContentService getContentService() {
return contentService;
}
public void setContentService(ContentService contentService) {
this.contentService = contentService;
}
}
How to create a new version of a file with the same name by using Java-backed WebScript?
Does this solution correct?
Check if the file exists by using Lucene search: TYPE:"firm:doc" AND #cm\:name:contract.png; (for example) If exists, increment the property cm:versionLabel and create a new version of Node with all the properties (Actually, need to iterate through all the ResultSet and find NodeRef with max value of cm:versionLabel then increment it and create a new Node). Is there more elegant solution?
The solution can be represented as follows:
public class CustomFileUploader extends DeclarativeWebScript {
private static final String FIRM_DOC = "{http://www.firm.com/model/content/1.0}doc";
private static final String FIRM_DOC_FOLDER = "workspace://SpacesStore/8caf07c3-6aa9-4a41-bd63-404cb3e3ef0f";
private FileFolderService fileFolderService;
private ContentService contentService;
private NodeService nodeService;
private SearchService searchService;
protected Map<String, Object> executeImpl(WebScriptRequest req, Status status) {
processUpload(req);
return null;
}
private void writeContent(NodeRef node, FirmFile firmFile) {
try {
ContentWriter contentWriter = contentService.getWriter(node, ContentModel.PROP_CONTENT, true);
contentWriter.setMimetype(firmFile.getFileMimetype());
contentWriter.putContent(firmFile.getFileContent().getInputStream());
} catch (Exception e) {
e.printStackTrace();
}
}
private NodeRef checkIfNodeExists(String fileName) {
StoreRef storeRef = new StoreRef(StoreRef.PROTOCOL_WORKSPACE, "SpacesStore");
ResultSet resultSet = searchService.query(storeRef, SearchService.LANGUAGE_LUCENE/*LANGUAGE_FTS_ALFRESCO*/,
"TYPE:\"firm:doc\" AND #cm\\:name:" + fileName.replaceAll(" ", "\\ ")+ "");
int len = resultSet.length();
if(len == 0) {
return null;
}
NodeRef node = resultSet.getNodeRef(0);
return node;
}
private NodeRef createNewNode(FirmFile firmFile) {
NodeRef parent = new NodeRef(FIRM_DOC_FOLDER);
NodeRef node = createFileNode(parent, firmFile.getFileName());
return node;
}
private void processUpload(WebScriptRequest req) {
FormData formData = (FormData) req.parseContent();
FormData.FormField[] fields = formData.getFields();
for(FormData.FormField field : fields) {
String fieldName = field.getName();
if(fieldName.equalsIgnoreCase("firm_file") && field.getIsFile()) {
String fileName = field.getFilename();
Content fileContent = field.getContent();
String fileMimetype = field.getMimetype();
NodeRef node = checkIfNodeExists(fileName);
// POJO
FirmFile firm = new FirmFile(fileName, fileContent, fileMimetype, FIRM_DOC);
if(node == null) {
node = createNewNode(firmFile);
}
writeContent(node, firmFile);
}
}
}
private NodeRef createFileNode(NodeRef parentNode, String fileName) {
try {
QName contentQName = QName.createQName(FIRM_DOC);
FileInfo fileInfo = fileFolderService.create(parentNode, fileName, contentQName);
return fileInfo.getNodeRef();
} catch (Exception e) {
e.printStackTrace();
}
}
public FileFolderService getFileFolderService() {
return fileFolderService;
}
public void setFileFolderService(FileFolderService fileFolderService) {
this.fileFolderService = fileFolderService;
}
public ContentService getContentService() {
return contentService;
}
public void setContentService(ContentService contentService) {
this.contentService = contentService;
}
public NodeService getNodeService() {
return nodeService;
}
public void setNodeService(NodeService nodeService) {
this.nodeService = nodeService;
}
public SearchService getSearchService() {
return searchService;
}
public void setSearchService(SearchService searchService) {
this.searchService = searchService;
}
}
The content model must have a mandatory aspect cm:versionable:
<mandatory-aspects>
<aspect>cm:versionable</aspect>
</mandatory-aspects>
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.
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;
}
}
}