Get text from xml - Android - java

I have this xml online http://64.182.231.116/~spencerf/test.xml
And I am trying to get the two text values Assorted Cereal and Yogurt Parfait (2). Here is how I am currently parsing it, and I get the values I want as well as all the values under then, all the numbers and such, but I just want to get the names, and I am struggling how to just do that, any help or guidance would be great. Here is my code:
String currentDay = "";
String currentMeal = "";
String counter = "";
String icon1 = "";
LinkedHashMap<String, List<String>> itemsByCounter = new LinkedHashMap<String , List<String>>();
List<String> items = new ArrayList<String>();
while (eventType != XmlResourceParser.END_DOCUMENT) {
String tagName = xmlData.getName();
switch (eventType) {
case XmlResourceParser.START_TAG:
if (tagName.equalsIgnoreCase("day")) {
currentDay = xmlData.getAttributeValue(null, "name");
}
if (tagName.equalsIgnoreCase("meal")) {
currentMeal = xmlData.getAttributeValue(null, "name");
}
if (tagName.equalsIgnoreCase("counter") && currentDay.equalsIgnoreCase(day) && currentMeal.equalsIgnoreCase(meal)) {
counter = xmlData.getAttributeValue(null, "name");
}
if (tagName.equalsIgnoreCase("name") && counter != null && currentDay.equalsIgnoreCase(day) && currentMeal.equalsIgnoreCase(meal)) {
icon1 = xmlData.getAttributeValue(null, "icon1");
Log.i(TAG, "icon1: " + icon1);
}
break;
case XmlResourceParser.TEXT:
if (currentDay.equalsIgnoreCase(day) && currentMeal.equalsIgnoreCase(meal) && counter !=(null)) {
if (xmlData.getText().trim().length() > 0) {
//Here gets everything but I just want 2 names
Log.i(TAG, "data: " + xmlData.getText());
items.add(xmlData.getText().trim().replaceAll(" +", " "));
}
}
break;
case XmlPullParser.END_TAG:
if (tagName.equalsIgnoreCase("counter")) {
if (items.size() > 0) {
itemsByCounter.put(counter, items);
items = new ArrayList<String>();
recordsFound++;
}
}
break;
}
eventType = xmlData.next();
So as you can see in the comment in my code I am getting everything under the name tag, back but I just want the value of the name, and not all the other stuff.

You will need to store the name in its own child element (meaning put an end tag before the nutritional facts). Under each dish, you could have this:
<name>Assorted Cereal</name>
<nutrition_facts> ... </nutrition_facts>

Not tested but could do it along these lines:
List<Nutrition_Facts> nutrition_facts = new ArrayList<Nutrition_Facts>();
XMLDOMParser parser = new XMLDOMParser();
AssetManager manager = context.getAssets();
InputStream stream;
try {
stream = manager.open("test.xml"); //need full path to your file here - mine is stored in assets folder
Document doc = parser.getDocument(stream);
}catch(IOException ex){
System.out.printf("Error reading map %s\n", ex.getMessage());
}
NodeList nodeList = doc.getElementsByTagName("nutrition_facts");
for (int i = 0; i < nodeList.getLength(); i++) {
Element e = (Element) nodeList.item(i);
String name;
if (elementName.equals(e.getAttribute("Assorted Cereal"))){
name = e.getAttribute("name");
//do some stuff
}
}
//XMLDOMParser Class
public class XMLDOMParser {
//Returns the entire XML document
public Document getDocument(InputStream inputStream) {
Document document = null;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = factory.newDocumentBuilder();
InputSource inputSource = new InputSource(inputStream);
document = db.parse(inputSource);
} catch (ParserConfigurationException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (SAXException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (IOException e) {
Log.e("Error: ", e.getMessage());
return null;
}
return document;
}
/*
* I take a XML element and the tag name, look for the tag and get
* the text content i.e for <employee><name>Kumar</name></employee>
* XML snippet if the Element points to employee node and tagName
* is name I will return Kumar. Calls the private method
* getTextNodeValue(node) which returns the text value, say in our
* example Kumar. */
public String getValue(Element item, String name) {
NodeList nodes = item.getElementsByTagName(name);
return this.getTextNodeValue(nodes.item(0));
}
private final String getTextNodeValue(Node node) {
Node child;
if (node != null) {
if (node.hasChildNodes()) {
child = node.getFirstChild();
while(child != null) {
if (child.getNodeType() == Node.TEXT_NODE) {
return child.getNodeValue();
}
child = child.getNextSibling();
}
}
}
return "";
}
}

Related

Replace Data to word Document In Alfresco using java code excluding junk characters

I am doing Bulk Upload Task in Alfresco.
Before this i created custom action to call java code, i also successfully read data from excel sheet, and i found node reference of target document as well as source Document. Using that node reference i am also able to create new multiple Documents.
Now My requirement is, I want to replace Excel Data in that newly created Document. I tried to replace it, But It replacing the String only in First line of document, and it also deleting Rest of the existing contents inside newly created document. I have written Below code for this.
In below code i am first simply trying to replace some hard coded data to the Document.
But My requirement is i want to replace the data inside document which i already read from excel file.
Java Code:
public class MoveReplacedActionExecuter extends ActionExecuterAbstractBase {
InputStream is;
Cell cell = null;
public static final String NAME = "move-replaced";
private FileFolderService fileFolderService;
private NodeService nodeService;
private ContentService contentService;
private SearchService searchService;
#Override
protected void addParameterDefinitions(List < ParameterDefinition > paramList) {
}
public void executeImpl(Action ruleAction, NodeRef actionedUponNodeRef) {
try {
ContentReader contentReader = contentService.getReader(actionedUponNodeRef, ContentModel.PROP_CONTENT);
is = contentReader.getContentInputStream();
} catch (NullPointerException ne) {
System.out.println("Null Pointer Exception" + ne);
}
try {
Workbook workbook = new XSSFWorkbook(is);
Sheet firstSheet = workbook.getSheetAt(0);
Iterator < Row > iterator = firstSheet.rowIterator();
while (iterator.hasNext()) {
ArrayList < String > al = new ArrayList < > ();
System.out.println("");
Row nextRow = iterator.next();
Iterator < Cell > cellIterator = nextRow.cellIterator();
while (cellIterator.hasNext()) {
cell = cellIterator.next();
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
System.out.print("\t" + cell.getStringCellValue());
al.add(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_BOOLEAN:
System.out.print("\t" + cell.getBooleanCellValue());
al.add(String.valueOf(cell.getBooleanCellValue()));
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print("\t" + cell.getNumericCellValue());
al.add(String.valueOf(cell.getNumericCellValue()));
break;
}
}
}
is.close();
} catch (Exception e) {
e.printStackTrace();
}
String query = "PATH:\"/app:company_home/cm:Dipak/cm:OfferLetterTemplate.doc\"";
SearchParameters sp = new SearchParameters();
StoreRef storeRef = new StoreRef(StoreRef.PROTOCOL_WORKSPACE, "SpacesStore");
sp.addStore(storeRef);
sp.setLanguage(SearchService.LANGUAGE_LUCENE);
sp.setQuery(query);
ResultSet resultSet = searchService.query(sp);
System.out.println("Result Set" + resultSet.length());
NodeRef sourceNodeRef = null;
for (ResultSetRow row: resultSet) {
NodeRef currentNodeRef = row.getNodeRef();
sourceNodeRef = currentNodeRef;
System.out.println(currentNodeRef.toString());
}
NodeRef n = new NodeRef("workspace://SpacesStore/78342318-37b8-4b42-aadc-bb0ed5d413d9");
try {
org.alfresco.service.cmr.model.FileInfo fi = fileFolderService.copy(sourceNodeRef, n, "JustCreated" + Math.random() + ".doc");
NodeRef newNode = fi.getNodeRef();
QName TYPE_AUTHORTY = QName.createQName("sunpharma.hr.model", "hrdoctype");
nodeService.setType(newNode, TYPE_AUTHORTY);
ContentReader contentReader1 = contentService.getReader(newNode, ContentModel.PROP_CONTENT);
InputStream is2 = contentReader1.getContentInputStream();
POIFSFileSystem fs = new POIFSFileSystem(is2);
HWPFDocument doc = new HWPFDocument(fs);
doc = replaceText1(doc, "Company", "Datamatics");
ContentWriter writerDoc = contentService.getWriter(newNode, ContentModel.PROP_CONTENT, true);
writerDoc.putContent(doc.getDocumentText());
} catch (FileExistsException | FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static HWPFDocument replaceText1(HWPFDocument doc, String findText, String replaceText) {
System.out.println("In the method replacetext" + replaceText);
Range r1 = doc.getRange();
System.out.println("Range of Doc : " + r1);
for (int i = 0; i < r1.numSections(); ++i) {
Section s = r1.getSection(i);
for (int x = 0; x < s.numParagraphs(); x++) {
Paragraph p = s.getParagraph(x);
for (int z = 0; z < p.numCharacterRuns(); z++) {
CharacterRun run = p.getCharacterRun(z);
String text = run.text();
if (text.contains(findText)) {
run.replaceText(findText, replaceText);
} else {
System.out.println("NO text found");
}
}
}
}
return doc;
}
public void setFileFolderService(FileFolderService fileFolderService) {
this.fileFolderService = fileFolderService;
}
public void setNodeService(NodeService nodeService) {
this.nodeService = nodeService;
}
public void setContentService(ContentService contentService) {
this.contentService = contentService;
}
public void setSearchService(SearchService searchService) {
this.searchService = searchService;
}
}
Its not possible to take direct file stream object in alfresco.
so i created one file at local drive, in background i performed all replacement operations. and after that i read all data using file input stream object. and later i used file that stream with node.
and it gave me my desired output. :)

How can get node child tag from xml with dom (Java)

Took a long time searching and watching videos.
I'm trying to access the course subjects ID
This is my xml code
<list>
<Asignatura>
<id>1</id>
<nombre>Programación</nombre>
<curso>
<id>1</id>
<nombre>1º DAM</nombre>
<listaAsignaturas>
<Asignatura reference="../../.."/>
<Asignatura>
<id>2</id>
<nombre>Bases de datos</nombre>
<curso reference="../../.."/>
<listaAlumnos/>
</Asignatura>
<Asignatura>
<id>3</id>
<nombre>Formación y orientación laboral</nombre>
<curso reference="../../.."/>
<listaAlumnos/>
</Asignatura>
<Asignatura>
<id>4</id>
<nombre>Entornos de desarrollo</nombre>
<curso reference="../../.."/>
<listaAlumnos/>
</Asignatura>
</listaAsignaturas>
</curso>
<listaAlumnos/>
</Asignatura>
</list>
And here my code in java
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse("./datos/Asignaturas.xml");
document.getDocumentElement().normalize();
NodeList Asignatura = document.getElementsByTagName("Asignatura");
for (int i = 0; i < Asignatura.getLength(); i++) {
Node c = Asignatura.item(i);
if (c.getNodeType() == Node.ELEMENT_NODE) {
Element elemento = (Element) c;
int id = Integer.parseInt(getValorHijo("id", elemento));
String nombre = getValorHijo("nombre", elemento);
//int idCurso = Integer.parseInt(getValorHijo("curso", elemento));
curso = new Curso();
curso.setId(idCurso);
curso = (Curso) FileXMLDAOFactory.getInstance().getCursoDAO().buscar(curso);
}
}
} catch (Exception e) {
e.printStackTrace();
}
I have to say it works, pick up the ID and name of the subject.
But I can not pick up the ID or name of the course subject that is within.
Im not have idea how can get it :(
I tried a slighty different approach with the same xml input file with the following code.
public static void main(String[] args) {
List<Assignatura> assignaturas = new ArrayList<Assignatura>();
List<Curso> cursos = new ArrayList<Curso>();
try{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder loader = factory.newDocumentBuilder();
Document document = loader.parse("datos.xml");
DocumentTraversal traversal = (DocumentTraversal) document;
NodeIterator iterator = traversal.createNodeIterator(
document.getDocumentElement(), NodeFilter.SHOW_ALL, new ListAsignaturasFilter(), true);
for (Node n = iterator.nextNode(); n != null; n = iterator.nextNode()) {
Element el = (Element) n;
NodeList assignments = el.getElementsByTagName("Asignatura");
for(int i=0; i<assignments.getLength(); i++){
Node currentNode = assignments.item(i);
NodeList childs = currentNode.getChildNodes();
String id = getValorHijo(childs, "id");
String nombre = getValorHijo(childs, "nombre");
if(!id.isEmpty() || !nombre.isEmpty())
assignaturas.add(new Assignatura(id, nombre));
}
}
NodeIterator itCurso = traversal.createNodeIterator(
document.getDocumentElement(), NodeFilter.SHOW_ALL, new CursoFilter(), true);
for (Node n = itCurso.nextNode(); n != null; n = itCurso.nextNode()) {
Element el = (Element) n;
NodeList cursos = el.getChildNodes();
String id = getValorHijo(cursos, "id");
String nombre = getValorHijo(cursos, "nombre");
if(!id.isEmpty() || !nombre.isEmpty())
cursos.add(new Curso(id, nombre));
}
for(Assignatura assignatura : assignaturas){
System.out.println(assignatura);
}
for(Curso curso : cursos){
System.out.println(curso);
}
}catch (Exception e) {
e.printStackTrace();
}
}
private static String getValorHijo(NodeList childs, String data){
String search="";
if(childs.getLength()>0)
for(int j=0; j<childs.getLength(); j++){
if(childs.item(j).getNodeName().equals(data)){
return childs.item(j).getTextContent();
}
}
return search;
}
private static final class ListAsignaturasFilter implements NodeFilter {
public short acceptNode(Node n) {
if (n instanceof Element) {
if (((Element) n).getTagName().equals("listaAsignaturas")) {
return NodeFilter.FILTER_ACCEPT;
}
}
return NodeFilter.FILTER_REJECT;
}
}
private static final class CursoFilter implements NodeFilter {
public short acceptNode(Node n) {
if (n instanceof Element) {
if (((Element) n).getTagName().equals("curso")) {
return NodeFilter.FILTER_ACCEPT;
}
}
return NodeFilter.FILTER_REJECT;
}
}
As you can see I created two lists to memorize "Assignatura" an "Curso" object which are simple POJO with two attributes id and nombre. At the end of the main method I display the content of these lists and I've got the id and nombre information of element "Curso" besides all "Asignatura" elements. Hope this code help you !
Just for the record. The use of DOM was compulsory ? Because, it would have been easier to use JAXB.

How to split a split a string twice

I am trying to split a string twice
String example = response;
String [] array = example.split("<section>");
System.out.println(array[0]);
String [] array2 = example.split("<title>");
System.out.println(array2[2]);
I am trying to achieve this by using this code (not successfully), but instead of printing the first split i want to save it and carry on with the 2nd split. whould anyone have a solution to ths problem or better way of going about splitting a string twice? thanks
This may seem like alot... but you should really be using a DOM parser for manipulating XML:
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXParseException;
public class ExtractXML {
public static void main(String argv[]) {
DocumentBuilderFactory docBuilderFactory = null;
DocumentBuilder docBuilder = null;
Document doc = null;
String rawStr = "Response: <section><title>Input interpretation</title>"
+ "<sectioncontents>Ireland</sectioncontents></section>"
+ "<section><title>Result</title>"
+ "<sectioncontents>Michael D. Higgins</sectioncontents></section>";
String docStr = rawStr.substring(rawStr.indexOf('<'));
String answer = "";
try {
docBuilderFactory = DocumentBuilderFactory.newInstance();
docBuilder = docBuilderFactory.newDocumentBuilder();
doc = docBuilder.parse(new InputSource(new StringReader(docStr)));
} catch (SAXParseException e) {
System.out.println("Doc missing root node, adding and trying again...");
docStr = String.format("<root>%s</root>", docStr);
try {
doc = docBuilder.parse(new InputSource(new StringReader(docStr)));
} catch (Exception e1) {
System.out.printf("Malformed XML: %s\n", e1.getMessage());
System.exit(0);
}
} catch (Exception e) {
System.out.printf("Something went wrong: %s\n", e.getMessage());
} finally {
try {
// Normalize text representation:
doc.getDocumentElement().normalize();
NodeList titles = doc.getElementsByTagName("title");
for (int tIndex = 0; tIndex < titles.getLength(); tIndex++) {
Node node = titles.item(tIndex);
if (node.getTextContent().equals("Result")) {
Node parent = node.getParentNode();
NodeList children = parent.getChildNodes();
for (int cIndex = 0; cIndex < children.getLength(); cIndex++) {
Node child = children.item(cIndex);
if (child.getNodeName() == "sectioncontents") {
answer = child.getTextContent();
}
}
}
}
System.out.printf("Answer: %s\n", answer);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Output:
[Fatal Error] :1:98: The markup in the document following the root element must be well-formed.
Doc missing root node, adding and trying again...
Answer: Michael D. Higgins
I really don't think you want use split here. I think you want to use something like
// Extract a given tag value from an input txt.
public static String extractTagValue(String txt,
String tag) {
if (tag == null || txt == null) {
return "";
}
String lcText = txt.toLowerCase();
tag = tag.trim().toLowerCase();
String openTag = "<" + tag + ">";
String closeTag = "</" + tag + ">";
int pos1 = lcText.indexOf(openTag);
if (pos1 > -1) {
pos1 += openTag.length();
int pos2 = lcText.indexOf(closeTag, pos1 + 1);
if (pos2 > -1) {
return txt.substring(pos1, pos2);
}
}
return "";
}
public static void main(String[] args) {
String example = "<title>Hello</title><section>World</SECTION>";
String section = extractTagValue(example,
"section");
String title = extractTagValue(example, "title");
System.out.printf("%s, %s\n", title, section);
}
Which, when executed, outputs
Hello, World

for loop inside try catch return without execute next line

I have a function for converting xml string to list array. while reaching the last condition,it jumps to the last return of the function.
The code does not execute the return statement after the for loop.and it does not execute any line after the for loop. It just execute the last return statement.
function is shown below
public List<List<String>> UpdateOrderDetailsTable(String xml) {
List<List<String>> ll = new ArrayList<List<String>>();
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
InputStream is = new ByteArrayInputStream(xml.getBytes("UTF-8"));
Document doc = dBuilder.parse(is);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("ProductDetails");
Log.i("1111",Integer.toString(nList.getLength()));
if (nList.getLength() > 0) {
// get all order details
//i=1 for neglect first tag
for (int i = 1; i < nList.getLength(); i++) {
Node nNode = nList.item(i);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
List<String> l = new ArrayList<String>();
l.add(0, eElement.getElementsByTagName("OrderId").item(0).getTextContent());
l.add(1, eElement.getElementsByTagName("ProductId").item(0).getTextContent());
l.add(2, eElement.getElementsByTagName("ProductName").item(0).getTextContent());
l.add(3, eElement.getElementsByTagName("Model").item(0).getTextContent());
l.add(4, eElement.getElementsByTagName("Quantity").item(0).getTextContent());
ll.add(l);
Log.i(Integer.toString(i),eElement.getElementsByTagName("OrderId").item(0).getTextContent());
}
}
return ll;
}
Log.i("2222222222222222222","222222222222222222");
} catch (Exception e) {
Log.e("11111", e.toString());
}
return null;
}
this is my xml
From your code, it can be deduced that the only case it will not execute any statement after for loop is that you are getting some EXCETPION. And as per your comments, you are saying you are not seeing any exception in the logs. Then i doubt your logger, for the sake of testing try to put some Sysout statements to make sure that logger is correct. Your log.e() method may not be working properly, just try to put your log.i() in the exception block and see.
Use i=0 operator
// get all order details
for (int i = 0; i < nList.getLength(); i++) {
}
}
If you don't want the first item, then change if (nList.getLength() > 0) statement to if (nList.getLength() > 1)
Also put an else statement for if (nNode.getNodeType() == Node.ELEMENT_NODE) and put a log output. E.g.:
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
List<String> l = new ArrayList<String>();
l.add(0, eElement.getElementsByTagName("OrderId").item(0).getTextContent());
l.add(1, eElement.getElementsByTagName("ProductId").item(0).getTextContent());
l.add(2, eElement.getElementsByTagName("ProductName").item(0).getTextContent());
l.add(3, eElement.getElementsByTagName("Model").item(0).getTextContent());
l.add(4, eElement.getElementsByTagName("Quantity").item(0).getTextContent());
ll.add(l);
Log.i(Integer.toString(i), eElement.getElementsByTagName("OrderId").item(0).getTextContent());
} else {
Log.wtf("1111", "Item " + i + "is not Node.ELEMENT_NODE type");
}
It just could be none of your nodes are type ELEMENT_NODE
public static ArrayList<ProductDetails> parserData(String data) {
XmlPullParserFactory factory = null;
XmlPullParser parser = null;
ArrayList<ProductDetails> productDetailsList = new ArrayList<ProductDetails>();
ProductDetails productDetails = null;
data = data.replaceAll("&", "&");
data = data.replaceAll("<BR />", "");
try {
factory = XmlPullParserFactory.newInstance();
parser = factory.newPullParser();
parser.setInput(new StringReader(data));
int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
if ("ProductDetails".equals(parser.getName())) {
productDetails = new ProductDetails();
} else if ("OrderId".equals(parser.getName())) {
productDetails.setOrderId(Integer.parseInt(parser.nextText()));
} else if ("ProductId".equals(parser.getName())) {
productDetails.setProductId(Integer.parseInt(parser.nextText()));
} else if ("ProductName".equals(parser.getName())) {
productDetails.setProductName(parser.nextText());
} else if ("Model".equals(parser.getName())) {
productDetails.setModel(parser.nextText());
} else if ("Quantity".equals(parser.getName())) {
productDetails.setQuantity(Integer.parseInt(parser.nextText()));
}
} else if (eventType == XmlPullParser.END_TAG) {
if ("ProductDetails".equals(parser.getName())) {
productDetailsList.add(productDetails);
}
}
eventType = parser.next();
}
System.out.println();
} catch (XmlPullParserException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
return productDetailsList;
}

XML parsing fails on Blackberry

I am using the following code for parsing an XML file. But I don't get any response. Can anyone help?
I am also getting a warning when I open a connection:
"Warning!: Invocation of questionable method: java.lang.String.() found"`?
public static void main(String arg[]){
XML_Parsing_Sample application = new XML_Parsing_Sample();
//create a new instance of the application
//and start the application on the event thread
application.enterEventDispatcher();
}
public XML_Parsing_Sample() {
_screen.setTitle("XML Parsing");//setting title
_screen.add(new RichTextField("Requesting....."));
_screen.add(new SeparatorField());
pushScreen(_screen); // creating a screen
//creating a connection thread to run in the background
_connectionthread = new Connection();
_connectionthread.start();//starting the thread operation
}
public void updateField(String node, String element){
//receiving the parsed node and its value from the thread
//and updating it here
//so it can be displayed on the screen
String title="Title";
_screen.add(new RichTextField(node+" : "+element));
if(node.equals(title)){
_screen.add(new SeparatorField());
}
}
private class Connection extends Thread{
public Connection(){
super();
}
public void run(){
// define variables later used for parsing
Document doc;
StreamConnection conn;
try{
//providing the location of the XML file,
//your address might be different
conn=(StreamConnection)Connector.open
("http://www.w3schools.com/xml/note.xml",Connector.READ);
//next few lines creates variables to open a
//stream, parse it, collect XML data and
//extract the data which is required.
//In this case they are elements,
//node and the values of an element
DocumentBuilderFactory docBuilderFactory
= DocumentBuilderFactory. newInstance();
DocumentBuilder docBuilder
= docBuilderFactory.newDocumentBuilder();
docBuilder.isValidating();
doc = docBuilder.parse(conn.openInputStream());
doc.getDocumentElement ().normalize ();
NodeList list=doc.getElementsByTagName("*");
_node=new String();
_element = new String();
//this "for" loop is used to parse through the
//XML document and extract all elements and their
//value, so they can be displayed on the device
for (int i=0;i<list.getLength();i++){
Node value=list.item(i).
getChildNodes().item(0);
_node=list.item(i).getNodeName();
_element=value.getNodeValue();
updateField(_node,_element);
}//end for
}//end try
//will catch any exception thrown by the XML parser
catch (Exception e){
System.out.println(e.toString());
}
}//end connection function
}// end connection class
You are probably timing out.
Try opening the connection as HTTP connection instead, and use the new ConnectionFactory class to get rid of annoying suffixes.
public InputStream getResult(String url) {
System.out.println("in get result");
HttpConnection httpConn;
httpConn = (HttpConnection) getHTTPConnection(url);
try {
if (httpConn != null) {
final int iResponseCode = httpConn.getResponseCode();
if (iResponseCode == httpConn.HTTP_OK) {
_inputStream = httpConn.openInputStream();
byte[] data = new byte[20];
int len = 0;
int size = 0;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
while (-1 != (len = _inputStream.read(data))) {
baos.write(data, 0, len);
size += len;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InputStream is2 = new ByteArrayInputStream(
baos.toByteArray());
return is2;
} else {
return null;
}
}
} catch (IOException e) {
System.err.println("Caught IOException: " + e.getMessage());
}
try {
httpConn.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
To download xml
To parse the downloaded xml.
public Document XMLfromInputStream(InputStream xml) {
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setAllowUndefinedNamespaces(true);
dbf.setCoalescing(true);
dbf.setExpandEntityReferences(true);
try {
DocumentBuilder db;
db = dbf.newDocumentBuilder();
InputSource _source = new InputSource();
_source.setEncoding("UTF-8");
_source.setByteStream(xml);
db.setAllowUndefinedNamespaces(true);
doc = db.parse(_source);
} catch (SAXException e) {
System.out.println("Wrong XML file structure: " + e.getMessage());
return null;
} catch (IOException e) {
System.out.println("I/O exeption: " + e.getMessage());
return null;
} catch (net.rim.device.api.xml.parsers.ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} finally {
}
return doc;
}
Then parse this document in to element
Element rootElement = document.getDocumentElement();
rootElement.normalize();
displayNode( rootElement, 0 );
private void displayNode( Node node, int depth )
{
if ( node.getNodeType() == Node.ELEMENT_NODE )
{
StringBuffer buffer = new StringBuffer();
indentStringBuffer( buffer, depth );
NodeList childNodes = node.getChildNodes();
int numChildren = childNodes.getLength();
Node firstChild = childNodes.item( 0 );
// If the node has only one child and that child is a Text node, then it's of
// the form <Element>Text</Element>, so print 'Element = "Text"'.
if ( numChildren == 1 && firstChild.getNodeType() == Node.TEXT_NODE )
{
buffer.append( node.getNodeName() ).append( " = \"" ).append( firstChild.getNodeValue() ).append( '"' );
add( new RichTextField( buffer.toString() ) );
}
else
{
// The node either has > 1 children, or it has at least one Element node child.
// Either way, its children have to be visited. Print the name of the element
// and recurse.
buffer.append( node.getNodeName() );
add( new RichTextField( buffer.toString() ) );
// Recursively visit all this node's children.
for ( int i = 0; i < numChildren; ++i )
{
displayNode( childNodes.item( i ), depth + 1 );
}
}
}
else
{
// Node is not an Element node, so we know it is a Text node. Make sure it is
// not an "empty" Text node (normalize() doesn't consider a Text node consisting
// of only newlines and spaces to be "empty"). If it is not empty, print it.
String nodeValue = node.getNodeValue();
if ( nodeValue.trim().length() != 0 )
{
StringBuffer buffer = new StringBuffer();
indentStringBuffer( buffer, depth );
buffer.append( '"' ).append( nodeValue ).append( '"' );
add( new RichTextField( buffer.toString() ) );
}
}
}
/**
* Adds leading spaces to the provided string buffer according to the depth of
* the node it represents.
*
* #param buffer The string buffer to add leading spaces to.
* #param depth The depth of the node the string buffer represents.
*/
private static void indentStringBuffer( StringBuffer buffer, int depth )
{
int indent = depth * _tab;
for ( int i = 0; i < indent; ++i )
{
buffer.append( ' ' );
}
}
You can download and parse the xml using above sample.
NamedNodeMap attributes = (NamedNodeMap)value.getAttributes();
for (int g = 0; g < attributes.getLength(); g++) {
Attr attribute = (Attr)attributes.item(g);
System.out.println(" Attribute: " + attribute.getName() +
" with value " +attribute.getValue());
Above code fetches attributes and its values.. cheers

Categories