capitalize first letter of a xml element - android

I'm a newbie so please be patient.
I have the following code retrieving the nodes and its fine. I've attempted to get the 'status' node to have it's first letter capitalized with little success, it force closes.
What I've done is convert the element to a string. I figured out that I could use the capitalization code for all the elements 'e' but I'd rather use it for status.
Why is it forcing close?
Could someone please help me with this?
NodeList nodes = doc.getElementsByTagName("line");
for (int i = 0; i < nodes.getLength(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element)nodes.item(i);
map.put("id", XMLFunctions.getValue(e, "id"));
map.put("name", XMLFunctions.getValue(e, "name"));
map.put("status", XMLFunctions.getValue(e, "status"));
map.put("message", XMLFunctions.getValue(e, "message"));
mylist.add(map);
//element to string
Document document = e.getOwnerDocument();
DOMImplementationLS domImplLS = (DOMImplementationLS) document
.getImplementation();
LSSerializer serializer = domImplLS.createLSSerializer();
String str = serializer.writeToString(e);
//capitalization
if (str.length() <= 1) {
str = str.toLowerCase();
} else {
str = str.substring(0, 1).toLowerCase() + str.substring(1);
}

Try this,
str = str.substring(0, 1).toLowerCase().concat(str.substring(1));

I solved this using the following code:
public static String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
char[] chars = XMLFunctions.getElementValue(n.item(0)).toLowerCase().toCharArray();
boolean found = false;
for (int i = 0; i < chars.length; i++) {
if (!found && Character.isLetter(chars[i])) {
chars[i] = Character.toUpperCase(chars[i]);
found = true;
} else if (Character.isWhitespace(chars[i]) || chars[i]=='.' || chars[i]=='\'') { // You can add other chars here
found = false;
}
}
return String.valueOf(chars);

Related

traverse nested xml file android

I'm trying to traverse a nested XML string in Android that looks like this:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Results>
<Result>
<Questions>
<Question>Where can I get the local variable</Question>
<Answer>In the local method</Answer>
<AverageRating>3.0</AverageRating>
</Questions>
<Keywords>
<Keyword>Methods</Keyword>
<Keyword>Returns</Keyword>
<Keyword>Void</Keyword>
</Keywords>
</Result>
<Result>
<Questions>
<Question>How can I do a nested for loop</Question>
<Answer>Easy</Answer>
<AverageRating>2.5</AverageRating>
</Questions>
<Keywords>
<Keyword>Methods</Keyword>
<Keyword>Returns</Keyword>
<Keyword>Void</Keyword>
<Keyword>Methods</Keyword>
<Keyword>Returns</Keyword>
</Keywords>
</Result>
with the following Android code:
try
{
//Creates the document
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(serverResult)));
//optional, but recommended
//read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
document.getDocumentElement().normalize();
//Look at root node's type (e.g. <query> or <login> or <add>)
String rootNode = document.getDocumentElement().getNodeName().toString();
if (rootNode.equals("Results"))
{
String Question = "";
String Answer = "";
String AverageRating = "";
float rating = 0;
String keyword = "";
NodeList nList = document.getElementsByTagName("Result");
for (int i = 0; i < nList.getLength(); i++)
{
Node nodes = nList.item(i);
if (nodes.getNodeType() == Node.ELEMENT_NODE)
{
Element element = (Element) nodes;
NodeList list = document.getElementsByTagName("Questions");
for (int value = 0; value < list.getLength(); value++)
{
Node node = list.item(value);
if (node.getNodeType() == Node.ELEMENT_NODE)
{
Element eElement = (Element) node;
Question = getValue("Question", eElement);
Answer = getValue("Answer", eElement);
AverageRating = getValue("AverageRating", eElement);
rating = Float.parseFloat(AverageRating);
}
}
}
NodeList keywordNode = document.getElementsByTagName("Keywords");
String keywords = "";
for (int y = 0; y < keywordNode.getLength(); y++)
{
Node node = keywordNode.item(y);
if (node.getNodeType() == Node.ELEMENT_NODE)
{
Element element = (Element) node;
NodeList ModList = document.getElementsByTagName("Keyword");
int count = ModList.getLength();
for (int b = 0; b < count; b++)
{
keyword = element.getElementsByTagName("Keyword").item(b).getTextContent();
keywords = keywords + keyword + "\n";
}
}
items.add(new Question(Question, Answer, rating, keywords));
}
}
}
}
catch (Exception e)
{
String s = e.getMessage();
publishProgress(s);
}
What I'm trying to achieve is for each question of each respective results in the Result tag of my XML, I want to get the question (and it's details) and the respective keywords, adding each to the Question class, then repeat for the next result from Results tag. Can someone please help with my code and show me where I'm going wrong?
Try importing these:
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
by downloading them at this site: http://www.xmlpull.org/
Then, try a code structure like this:
String XMLin;
XmlPullParserFactory factory;
String tag;
ArrayList<Question> questions = new ArrayList<Question>();
try {
XMLin = readString(instream);
} catch (IOException e1) {
// TODO Auto-generated catch block
XMLin = "Something went wrong";
}
try {
// Set up the Class that will be parsing the xml file
factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(new StringReader (XMLin));
// Get the first event type
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
// While we have not reached the end of the document, check for start tags
if (eventType == XmlPullParser.START_TAG) {
tag = xpp.getName();
if (tag.equals("Questions") && eventType == XmlPullParser.START_TAG) {
Question question = new Question();
do {
if (tag.equals("Question")) {
// Add question text to question
eventType = xpp.next();
String text = xpp.getText(); // Text between tags
} else if (tag.equals("Answer")) {
eventType = xpp.next();
String text = xpp.getText(); // Text between tags
} else if (tag.equals("AvergaeRating") {
eventType = xpp.next();
String text = xpp.getText(); // Text between tags
}
eventType = xpp.next();
if (eventType == XmlPullParser.TEXT) {
tag = xpp.getText();
} else {
tag = xpp.getName();
}
} while (!tag.equals("Questions"))
questions.add(question);
}
}
}
This is a modified example of something I used to parse through XML. Essentially, check for the tag name and event (whether it's a start tag or end tag, etc) and then perform that actions you want depending on those two values, such as add the text inbetween into a Question object or whatnot.
I managed to use this code:
try
{
//Creates the document
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(serverResult)));
//optional, but recommended
//read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
document.getDocumentElement().normalize();
//Look at root node's type (e.g. <query> or <login> or <add>)
String rootNode = document.getDocumentElement().getNodeName().toString();
if (rootNode.equals("Results"))
{
//Any methods which need to be called that will be used to query the database
//Always sending the String XML through as a parameter
//Look at the child node
String Question = "";
String Answer = "";
String AverageRating = "";
float rating = 0;
String keywords = "";
NodeList nList = document.getElementsByTagName("Questions");
System.out.println("----------------------------");
for (int temp = 0; temp < nList.getLength(); temp++)
{
Node nNode = nList.item(temp);
System.out.println("\nCurrent Element :" + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE)
{
Element eElement = (Element) nNode;
Question = getValue("Question", eElement);
Answer = getValue("Answer", eElement);
AverageRating = getValue("AverageRating", eElement);
rating = Float.parseFloat(AverageRating);
NodeList List = document.getElementsByTagName("Keywords");
for (int a = 0; a < List.getLength(); a++)
{
Node node = List.item(temp);
if (node.getNodeType() == Node.ELEMENT_NODE)
{
Element element = (Element) node;
String Keyword = element.getElementsByTagName("Keyword").item(0).getTextContent();
keywords = keywords + Keyword + "\n";
}
}
}
items.add(new Question(Question, Answer, rating, keywords));
}
}
}
catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
which then get's each individual question (and all their information - question, answer, rating) and well as the respective keywords for that question and add to a Question object, then loop back. I wasn't putting the keywords XML parse within the questions for loop. Hopefully this helps someone who is struggling with similar problems.

Getting specific Node Value from XML and add to ArrayLIst

I have an XML like this
<reg>
<user>
<Name> abc</Name>
<Email> abc#xyz.com</Email>
<picture> sdCard/imges.145.jpg </Picture>
<Date> 12/12/2012</Date>
</user>
<user>
<Name> abc dfg</Name>
<Email> ertdg#xyz.com</Email>
<picture> sdCard/imges.145.jpg </Picture>
<Date> 23/12/2013</Date>
</user>
</reg>
i want to get values of specific nodes and add them to ArrayList to show the in ListView
I have tried this code but it only gives values for Last Record
Users setUser = new Users();
final ArrayList<Users> uData = new ArrayList<Users>();
Document xmlDocument = builder.parse(file);
XPath xPath = XPathFactory.newInstance().newXPath();
String expression = "/reg/user/Name";
System.out.println(expression);
NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
System.out.println(nodeList.item(i).getTextContent());
setUser.setName(nodeList.item(i).getTextContent());
}
String expression1 = "/reg/user/Email";
System.out.println(expression1);
NodeList nodeList1 = (NodeList) xPath.compile(expression1).evaluate(xmlDocument, XPathConstants.NODESET);
for (int i = 0; i < nodeList1.getLength(); i++) {
System.out.println(nodeList1.item(i).getTextContent());
setUser.setEmail(nodeList1.item(i).getTextContent());
}
String expression2 = "/reg/user/Picture";
System.out.println(expression2);
NodeList nodeList2 = (NodeList) xPath.compile(expression2).evaluate(xmlDocument, XPathConstants.NODESET);
for (int i = 0; i < nodeList2.getLength(); i++) {
System.out.println(nodeList2.item(i).getTextContent());
setUser.setimage(nodeList2.item(i).getTextContent());
}
String expression3 = "/reg/user/LastEdited";
System.out.println(expression3);
NodeList nodeList3 = (NodeList) xPath.compile(expression3).evaluate(xmlDocument, XPathConstants.NODESET);
for (int i = 0; i < nodeList3.getLength(); i++) {
System.out.println(nodeList3.item(i).getTextContent());
setUser.setDate(nodeList3.item(i).getTextContent());
} uData.add(setUser);
How can i make this to show all records ?
The reason why your code only gives values for Last Record already explained by #playmaker420 in comment. To fix it, you can try to loop through <user> elements instead of looping through each <name>, <email>, <picture>, and <date> separately :
XPath xPath = XPathFactory.newInstance().newXPath();
String expression = "/reg/user";
NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
Users setUser = new Users();
Element el = (Element) nodeList.item(i);
String name = el.getElementsByTagName("Name").item(0).getTextContent();
setUser.setName(name);
String email = el.getElementsByTagName("Email").item(0).getTextContent();
setUser.setEmail(email);
String picture = el.getElementsByTagName("picture").item(0).getTextContent();
setUser.setimage(picture);
String date = el.getElementsByTagName("Date").item(0).getTextContent();
setUser.setDate(date);
uData.add(setUser);
}

xml parsing and show the data in a list view

I have a xml file like [this][1] and i need to get the all the "edition name" according to the "group name"
I have to create a list of group name and show the list of editions name on clicking of the group name.
OutPut :
onclick of catalogs :
this xml is present in different languages, is there any way to get all the editions name without comparing with group name.
currently i am using type tag to get all the catalogs
:
if(parser.getValue(ele2, "type").toString().equalsIgnoreCase("catalog"))
But some magazines are also present in catalogs type. so not getting correct results
..
How to get all the editions name where group name is catalogs and so on ...
Or a better way to do so.. I am not sure the code I am using is a good approach.
Kindly suggest.
My code :
final String URL = "http://xml/web/?frg="+lang+"&user="+count+"_"+user;
System.out.println("URL child : " + URL);
parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML from URL
doc = parser.getDomElement(xml); // getting DOM element
NodeList n1 = doc.getElementsByTagName("groups");
for (int i = 0; i < 1; i++) { //ToDo : worked temp
Element e = (Element) n1.item(0);
NodeList children = e.getChildNodes();
if(item_name.equalsIgnoreCase("Catalogs")||item_name.equalsIgnoreCase("Kataloge")) // there could be other languages
{
NodeList nodeList2 = doc.getElementsByTagName("edition");
for (int k = 0; k < nodeList2.getLength(); k++) {
HashMap<String, String> map = new HashMap<String, String>();
Element ele2 = (Element) nodeList2.item(k);
if(parser.getValue(ele2, "type").toString().equalsIgnoreCase("catalog"))
{
System.out.println(""+parser.getValue(ele2, "name").toString());
System.out.println(""+parser.getValue(ele2, "cat_url").toString());
map.put(ss2, parser.getValue(ele2,ss2 ));
map.put(KEY_THUMB_URL, parser.getValue(ele2, KEY_THUMB_URL));
map.put(CAT_URL, parser.getValue(ele2,"cat_url"));
// adding HashList to ArrayList
songsList.add(map);
}
}
}
if(item_name.equalsIgnoreCase("Magazines")||item_name.equalsIgnoreCase("Magazine"))
{
NodeList nodeList2 = doc.getElementsByTagName("edition");
for (int k = 0; k < nodeList2.getLength(); k++) {
HashMap<String, String> map = new HashMap<String, String>();
Element ele2 = (Element) nodeList2.item(k);
if(parser.getValue(ele2, "type").toString().equalsIgnoreCase("pdf"))
{
System.out.println(""+parser.getValue(ele2, "name").toString());
System.out.println(""+parser.getValue(ele2, "cat_url").toString());
map.put(ss2, parser.getValue(ele2,ss2 ));
map.put(KEY_THUMB_URL, parser.getValue(ele2, KEY_THUMB_URL));
map.put(CAT_URL, parser.getValue(ele2,"cat_url"));
// adding HashList to ArrayList
songsList.add(map);
}
}
}
if(item_name.equalsIgnoreCase("Instructions"))
{
NodeList n2 = doc.getElementsByTagName("groups");
for (int i1 = 0; i1 < 1; i1++) { //ToDo : worked temp
Element e1 = (Element) n2.item(0);
NodeList children1 = e1.getChildNodes();
for (int j = 0; j <children1.getLength(); j++) {
HashMap<String, String> map = new HashMap<String, String>();
child = children1.item(j);
// System.out.println("name node22 inside " + parser.getValue((Element)child, "name"));
if(parser.getValue((Element)child, "name").equals("Instructions"))
{
if (child.getNodeName().equalsIgnoreCase("group")) {
NodeList nl2 = child.getChildNodes();
System.out.println("Nodelist lenght : " + nl2.getLength());
for (int jj = 0; jj <nl2.getLength(); jj++) {
Node nn =nl2.item(jj);
System.out.println("name node22 inside " + parser.getValue((Element)nn, "name"));
}
// map.put(KEY_TITLE, parser.getValue((Element)child,KEY_TITLE ));
//map.put(KEY_THUMB_URL, parser.getValue((Element)child, KEY_THUMB_URL));
// adding HashList to ArrayList
//songsList.add(map);
}
}
}
}
}
Solved :
Changed this :
Element e = (Element) n1.item(0);
NodeList nodeList2 = doc.getElementsByTagName("edition");
to this :
Element e = (Element) n1.item(0);
NodeList nodeList2 = e.getElementsByTagName("edition");
I'd rather suggest you to build your own parser using the pattern matching approach. Coz it gives you the power to customize things according to your need.
Gson like parser will be a good fit.

Recover multiple data from json

I'm trying to parse a json inside an HashMap to use the data inside my app.
Here is a simplified version of the code:
JSONArray array1 = new JSONArray(json);
for (int i = 0; i < array1.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject object1 = array1.getJSONObject(i);
JSONObject object2 = object1.getJSONObject("job");
JSONArray array2 = object2.getJSONArray("formations");
if (array2.length() != 0) {
for (int i1 = 0; i1 < array2.length() - 1; i1++) {
JSONObject object3 = array2.getJSONObject(i1);
map.put("formation-created_at",
}
}
map.put("testimony", object2.getString("testimony"));
JSONArray array3 = object2.getJSONArray("themes");
if (array3.length() != 0) {
for (int i2 = 0; i2 < array3.length() - 1; i2++) {
JSONObject object4 = array3.getJSONObject(i2);
map.put("themes-intro", object4.getString("intro"));
}
}
JSONObject object5 = object2.getJSONObject("sector");
map.put("sector-description", object5.getString("description"));
list.add(map);
}
Log.d("testimony", list.get(1).get("testimony"));
Log.d("themes-intro", list.get(1).get("themes-intro"));
I can recover the first object in the map with :
Log.d("testimony", list.get(1).get("testimony"));
But i cannot recover the one who is inside the loop :
Log.d("themes-intro", list.get(1).get("themes-intro"));
The logcat return the error :
FATAL EXCEPTION: main
java.lang.NullPointerException: println needs a message
at android.util.Log.println_native(Native Method)
at android.util.Log.d(Log.java:138)
I know that I should specify which "themes-intro" I want to call from the loop, but I cannot add a .get(x) to the expression.
Edit :
Here is the full json : http://komfushee.com/documents/ctai/jobs.json
And I've edited my code to give the full version of the code
please use below code i think i hope it will be haplfull....
HashMap<String, String> map1 = new HashMap<String, String>();
HashMap<String, String> map2 = new HashMap<String, String>();
if (array1.length() != 0) {
for (int i = 0; i < array1.length(); i++) {
JSONObject object1 = array1.getJSONObject(i);
JSONObject object2 = object1.getJSONObject("job");
map1.put("testimony", object2.getString("testimony"));
}
}
if (array2.length() != 0) {
for (int i1 = 0; i1 < array2.length() - 1; i1++) {
JSONObject object3 = array2.getJSONObject(i1);
map2.put("formation-created_at", object3.getString("created_at"));
}
}

Dom parsing in android

i have parsed xml using dom parser,but when the xml element contains no value it throws null pointer Exception.how to check this?...
here my code
NodeList TrackName1 = fstElmnt2.getElementsByTagName("Artist_Name");
Element TrackElement1 = (Element) TrackName1.item(0);
TrackName1 = TrackElement1.getChildNodes();
result=result+((Node) TrackName1.item(0)).getNodeValue()
String Artistname=((Node)TrackName1.item(0)).getNodeValue();
}
Just check for null before you try to use the value?
Object value = ((Node) TrackName1.item(0)).getNodeValue();
if (value != null) {
result = result + value;
}
NodeList nodeList = doc.getElementsByTagName("item");
description = new TextView[nodeList.getLength()];
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
description[i] = new TextView(this);
Element fstElmnt = (Element) node;
NodeList dataList = fstElmnt.getElementsByTagName("description");
Element dataElement = (Element) dataList.item(0);
dataList = dataElement.getChildNodes();
description[i].setText( ((Node) dataList.item(0)).getNodeValue());

Categories

Resources