How to Parse XML special characters from service by utf-8 encoding - android

I want to parse "ALışVERIş" type of content from service.
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
myXMLHandler = new XMLHandler();
xr.setContentHandler(myXMLHandler);
URL _url = new URL(params[0]);
xr.parse(new InputSource(_url.openStream()));

What I tried DOM Parser instead of XaxParser. Check below function and call it inside background thread :
public String readXML(){
StringBuilder stringBuilder = new StringBuilder();
try {
URL _url = new URL("http://182.160.161.2/~siva/turkish/web_serv/category.php?order_by=desc&category_id=2");
File fXmlFile = new File(new InputSource(_url.openStream()).getByteStream().toString());
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new InputSource(_url.openStream()).getByteStream());
//optional, but recommended
//read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("document");
Node nResp = nList.item(0);
Element fstElmnt = (Element) nResp;
NodeList nameList1 = fstElmnt.getElementsByTagName("response");
Node mCat = nameList1.item(0);
Element catElmt = (Element) mCat;
NodeList catList = catElmt.getElementsByTagName("category");
System.out.println("----------------------------");
for (int temp = 0; temp < catList.getLength(); temp++) {
Node nNode = catList.item(temp);
System.out.println("\nCurrent Element :" + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
stringBuilder.append("Category ID : " + eElement.getElementsByTagName("category_name").item(0).getTextContent()+"\n");
stringBuilder.append("Category Name : " + eElement.getElementsByTagName("category_id").item(0).getTextContent());
System.out.println("Category ID : " + eElement.getElementsByTagName("category_name").item(0).getTextContent());
System.out.println("Category Name : " + eElement.getElementsByTagName("category_id").item(0).getTextContent());
}
}
} catch (Exception e) {
e.printStackTrace();
}
return stringBuilder.toString();
}
Here is a screenshot of my device, Have a look :
You can see those turkish language too :)

Related

How to remove node from xml?

I have xml:
<Info>
<info_1/>
<info_2/>
<info_3>
<i ID="1"/>
<i ID="2"/>
<i ID="3"/>
</info_3>
<info_4>
</indo_4>
</Info>
I need to delete a specific node in info_3, for example a node in which ID = 1, how can I do this?
I tried to do this, but log shows before and after length = 3 :
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new InputSource(new StringReader(bb)));
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("i");
Log.e("LOG", "nList.getLength() = " + nList.getLength());
Node node=nList.item(1);
node.getParentNode().removeChild(node);
Log.e("LOG", "nList.getLength() = " + nList.getLength());
Solution that helped me:
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new InputSource(new StringReader(bb)));
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("i");
Log.e("LOG", "nList.getLength() = " + nList.getLength());
Set<Element> targetElements = new HashSet<>();
for (int i = 0; i < nList_Loan_guarantor.getLength(); i++) {
Element e = (Element)nList_Loan_guarantor.item(i);
if ("10938".equals(e.getAttribute("ID"))) {
targetElements.add(e);
}
}
for (Element e: targetElements) {
e.getParentNode().removeChild(e);
}
doc.getDocumentElement().normalize();
NodeList nList_2 = doc.getElementsByTagName("i");
Log.e("LOG", "nList.getLength() = " + nList.getLength());

how to use listView with parsed strings in Android?

Here is my code. I want to see these parsed strings into ListView in Android. How can I do this?
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xmlRecords));
Document doc = db.parse(is);
NodeList nodes = doc.getElementsByTagName("employee");
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
NodeList name = element.getElementsByTagName("name");
Element line = (Element) name.item(0);
System.out.println("Name: " + getCharacterDataFromElement(line));
NodeList title = element.getElementsByTagName("title");
line = (Element) title.item(0);
System.out.println("Title: " + getCharacterDataFromElement(line));
}
}
public static String getCharacterDataFromElement(Element e) {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return "";
}
}

Doc xml Parser android local xml file reading

I have one local xml file. I am storing here : res/xml/myxml.xml
<?xml version="1.0" encoding="utf-8"?>
<list>
<lists>
<tag>College Website</tag>
<value>http://www.nitk.ac.in/</value>
<lastupdate>04-07-2012</lastupdate>
</lists>
<lists>
<tag>College Images</tag>
<value>http://studentsworld.nitk.ac.in/index.php?q=convocation.html</value>
<lastupdate>25-9-2011</lastupdate>
</lists>
</list>
I have doc for loop. but how to connect local xml file in doc parser. i don't want url model, i want to a local xml file.
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
tag[i] = new TextView(this);
value[i] = new TextView(this);
lastupdate[i] = new TextView(this);
Element fstElmnt = (Element) node;
NodeList nameList = fstElmnt.getElementsByTagName("tag");
Element nameElement = (Element) nameList.item(0);
nameList = nameElement.getChildNodes();
tag[i].setText("tag = " + ((Node) nameList.item(0)).getNodeValue());
NodeList websiteList = fstElmnt.getElementsByTagName("value");
Element websiteElement = (Element) websiteList.item(0);
websiteList = websiteElement.getChildNodes();
value[i].setText("value = " + ((Node) websiteList.item(0)).getNodeValue());
NodeList lastupdateList = fstElmnt.getElementsByTagName("tag");
Element lastupdateElement = (Element) lastupdateList.item(0);
lastupdateList = lastupdateElement.getChildNodes();
lastupdate[i].setText("lastupdate = " + ((Node) lastupdateList.item(0)).getNodeValue());
layout.addView(tag[i]);
layout.addView(value[i]);
layout.addView(lastupdate[i]);
}
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
I have main.xml file
please send me a code
put you XML file in assets folder and try this
InputStream raw = getApplicationContext().getAssets().open("simple.xml");
and try this
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder= dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(raw);
....
...
put you XML file in assets folder and Try this way
String xml;
Document doc;
try{
xml=getXML(getAssets().open("yourxmlfilename.xml"));
}catch(Exception e){
Log.d("Error",e.toString());
}
doc = XMLfromString(xml);
where getXML and XMLfromString method are as shown below
//getXML method
public static String getXML(InputStream is)throws IOException {
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayOutputStream buf = new ByteArrayOutputStream();
int result = bis.read();
while(result != -1) {
byte b = (byte)result;
buf.write(b);
result = bis.read();
}
return buf.toString();
}
//XMLfromString method
public final static Document XMLfromString(String xml){
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
} catch (ParserConfigurationException e) {
System.out.println("XML parse error: " + e.getMessage());
return null;
} 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;
}
return doc;
}
please use below code for parse local xml,
InputStream in = this.getResources().openRawResource(R.raw.xmlfile);
And then parse inputstream,
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance ();
DocumentBuilder db = dbf.newDocumentBuilder ();
Document document = db.parse(in, null);

Can't parse XML with DOM in android

I am having some trouble parsing XML in Android from an URL. I don't know if it's the XML parsing that's the problem or only when I am trying to show it on the screen because
setListAdapter(new ArrayAdapter<String>(ANDROIDXMLActivity.this, android.R.layout.simple_list_item_1, stopNumbers));
wont show anything. The code below works perfectly in a java program.
URL: http://maps.travelsouthyorkshire.com/iGNMSearchService.asmx/FindObjectsWithinExtent?xMin=435360&yMin=387260&xMax=435960&yMax=387860&zoomLevel=0
try {
ArrayList<Double> xCords = new ArrayList<Double>();
ArrayList<Double> yCords = new ArrayList<Double>();
ArrayList<String> stopNumbers = new ArrayList<String>();
ArrayList<String> bussLocations = new ArrayList<String>();
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder
.parse(new URL(
"http://maps.travelsouthyorkshire.com/iGNMSearchService.asmx/FindObjectsWithinExtent?xMin=435360&yMin=387260&xMax=435960&yMax=387860&zoomLevel=0")
.openStream());
// normalize text representation
doc.getDocumentElement().normalize();
NodeList listOfObjects = doc.getElementsByTagName("iGNMObject");
for (int s = 0; s < listOfObjects.getLength(); s++) {
Node firstPersonNode = listOfObjects.item(s);
if (firstPersonNode.getNodeType() == Node.ELEMENT_NODE) {
Element firstPersonElement = (Element) firstPersonNode;
NodeList stopNumList = firstPersonElement
.getElementsByTagName("StopNumber");
Element ageElement = (Element) stopNumList.item(0);
if (ageElement != null) {
NodeList textAgeList = ageElement.getChildNodes();
String stop = ((Node) textAgeList.item(0))
.getNodeValue().trim();
stopNumbers.add(stop);
// ------
// -------
NodeList xPosList = firstPersonElement
.getElementsByTagName("XPosition");
Element firstNameElement = (Element) xPosList.item(0);
NodeList textFNList = firstNameElement.getChildNodes();
String temp2 = ((Node) textFNList.item(0))
.getNodeValue().trim();
double x = Double.parseDouble(temp2);
xCords.add(x);
// -------
NodeList yPosList = firstPersonElement
.getElementsByTagName("YPosition");
Element lastNameElement = (Element) yPosList.item(0);
NodeList textLNList = lastNameElement.getChildNodes();
String temp3 = ((Node) textLNList.item(0))
.getNodeValue().trim();
double y = Double.parseDouble(temp3);
yCords.add(y);
// ----
NodeList stopAkaList = firstPersonElement
.getElementsByTagName("StopAka");
Element stopAka = (Element) stopAkaList.item(0);
NodeList textStopAKAList = stopAka.getChildNodes();
String plats = ((Node) textStopAKAList.item(0))
.getNodeValue().trim();
bussLocations.add(plats);
} else {
}
}// end of if clause
}// end of for loop with s var
setListAdapter(new ArrayAdapter<String>(ANDROIDXMLActivity.this,
android.R.layout.simple_list_item_1, stopNumbers));
} catch (Exception e) {
}
}
}
}
Solved it. I had forgot to add internet permission in the manifest.

XML Parsing Error

I am consuming a web service as its output is an XML string. I am parsing it into a document and getting each child node value one by one and inserting into my SQLlite table as shown below:
public void DownloadAndInsertProblemAndReasonCode(String serverIPAddress,
String deviceId) {
String SOAP_ACTION = "http://VisionEPODWebService/GetProblemAndReasonCodesNew";
String OPERATION_NAME = "GetProblemAndReasonCodesNew";
String WSDL_TARGET_NAMESPACE = "http://VisionEPODWebService/";
String SOAP_ADDRESS = "";
SOAP_ADDRESS = "http://" + serverIPAddress
+ "/VisionEPODWebService/SystemData.asmx";
SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE,
OPERATION_NAME);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER10);
request.addProperty("deviceID", deviceId);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS);
try {
httpTransport.call(SOAP_ACTION, envelope);
Object response = envelope.getResponse();
DocumentBuilderFactory docBuilberFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder docBuilder = docBuilberFactory.newDocumentBuilder();
InputSource inputSource = new InputSource();
inputSource
.setCharacterStream(new StringReader(response.toString()));
Document doc = docBuilder.parse(inputSource);
NodeList nodesProblemCode = doc
.getElementsByTagName("tblProblemCode");
ContentValues initialProblemCodeValues = new ContentValues();
dbAdapter = new DatabaseAdapter(this.context);
dbAdapter.open();
dbAdapter.BeginTransaction();
dbAdapter.DeleteRecord("tblProblemCode", "", "");
for (int i = 0; i < nodesProblemCode.getLength(); i++) {
Element element = (Element) nodesProblemCode.item(i);
NodeList PKProblemCode = element
.getElementsByTagName("PKProblemCode");
Element line = (Element) PKProblemCode.item(0);
initialProblemCodeValues.put("PKProblemCode",
getCharacterDataFromElement(line).toString());
NodeList ProblemCode = element
.getElementsByTagName("ProblemCode");
line = (Element) ProblemCode.item(0);
initialProblemCodeValues.put("ProblemCode",
getCharacterDataFromElement(line));
NodeList ProblemCodeDescription = element
.getElementsByTagName("ProblemCodeDescription");
line = (Element) ProblemCodeDescription.item(0);
initialProblemCodeValues.put("ProblemCodeDescription",
getCharacterDataFromElement(line).toString());
NodeList VWReturn = element.getElementsByTagName("VWReturn");
line = (Element) VWReturn.item(0);
initialProblemCodeValues.put("VWReturn",
getCharacterDataFromElement(line).toString());
dbAdapter.InsertRecord("tblProblemCode", "",
initialProblemCodeValues);
}
NodeList nodesReasonCode = doc
.getElementsByTagName("tblReasonCode");
ContentValues initialReasonCodeValues = new ContentValues();
dbAdapter.DeleteRecord("tblReasonCode", "", "");
for (int i = 0; i < nodesReasonCode.getLength(); i++) {
Element element = (Element) nodesReasonCode.item(i);
NodeList PKReasonCode = element
.getElementsByTagName("PKReasonCode");
Element line = (Element) PKReasonCode.item(0);
initialReasonCodeValues.put("PKReasonCode",
getCharacterDataFromElement(line).toString());
NodeList ReasonDescription = element
.getElementsByTagName("ReasonDescription");
line = (Element) ReasonDescription.item(0);
initialReasonCodeValues.put("ReasonDescription",
getCharacterDataFromElement(line));
dbAdapter.InsertRecord("tblReasonCode", "",
initialReasonCodeValues);
}
dbAdapter.SetSucessfulTransaction();
dbAdapter.EndTransaction();
dbAdapter.close();
}
catch (Exception exception) {
exception.toString();
}
}
public static String getCharacterDataFromElement(Element e) {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return "?";
}
The problem is that after some time the XML string will not have some of child node. For example
"ProblemCode" child node.....at that time the code shows error.
How can I check whether there exists an element in the document, or whether values exist or not for the element?
I think you need to check if the child node exists: specifically for your problem node:
NodeList NL = element.getElementsByTagName("PKProblemCode");
if ((NL==null)||(NL.getLength()==0)) {
//No such node so use a default instead
} else
Element line = (Element) PKProblemCode.item(0);

Categories

Resources