How to retrieve xml elements in android using DOM - android

I have created an xml file and stored in my sdcard.I am using DOM parser to retrieve it.My xml file is like.I have used a simple xml file for demo.It is:
<?xml version="1.0"?>
<root>
<staff>
<word>1</word>
<meaning>one</meaning>
</staff>
<staff>
<word>2</word>
<meaning>two</meaning>
</staff>
</root>
In my activity i have an autocompletetextview.In it when i enter 1 which is given in word it should show the value "one" which is given in its meaning.Is it possible to do this and how?

Get node list by using getElementsByTagName("staff")
get child nodes getChildNodes()
Now get nodename getNodeName() and node value getNodeValue()
See this below code:
Element root=doc.getDocumentElement();
NodeList nodeList=root.getElementsByTagName("staff");
for(int i=0;i<nodeList.getLength();i++)
{
Node statenode=nodeList.item(i);
NodeList idList= statenode.getChildNodes();
for(int j=0;j<idList.getLength();j++)
{
Node property = idList.item(j);
String name = property.getNodeName();
if (name.equalsIgnoreCase("word"))
{
//Read your values here
Log.e("",property.getFirstChild().getNodeValue());
}
if (name.equalsIgnoreCase("meaning"))
{
//Read your values here
Log.e("",property.getFirstChild().getNodeValue());
}
}
}

Related

Need to trim a xml content from Aadhar scanned data

I'm trying to scan an Aadhar card data and trying to parse the given data into my app. I'm getting the response as follows.
QR-Code:<?xml version="1.0" encoding="UTF-8"?> <PrintLetterBarcodeData uid=“xxxxxxx” name=“xx” gender=“XXXX” yob=“xxxx” co="S/O: XXXX” house=“XXXX house” street="null" lm="null" loc="null" vtc=“xxx” po=“xxx” dist=“xxx” subdist=“xxx” state=“xxx” pc=“xxx” dob=“xxxx-xx-xx”/>
I need to trim the content QR-Code:<?xml version="1.0" encoding="UTF-8"?>.
Is it possible?
Split using ":" then parse the remaining XML
String[] data = result.split(":");
String xml = data[1];
public String trimStart(String qrCodeScanResponse){
return qrCodeScanResponse.replace("QR-Code:<?xml version=\"1.0\" encoding=\"UTF-8\"?>","");
}
// 'c' contains your xml data
var currLoanXml = c;
var uid = $(currLoanXml).filter('PrintLetterBarcodeData').attr('uid');
document.getElementById('aadhar').value=uid;
Here I chosen uid number, you can choose any attribute as per your need

Extracting xml contents using DOM, how do I separately extract the textcontent of the following childnode

I am extracting xml content using DOM, a particular node "#cdata-section" has the following output that I have attached the logcat output."#cdata-section" its TextContent is the logcat output. The textcontent has tag elements and I want to separately exact the tag from the output. How I am suppose to do that plz help.
xml file=http://myimagefactorycollection.wordpress.com/feed/
DocumentBuilderFactory DBF=DocumentBuilderFactory.newInstance();
DocumentBuilder Db=DBF.newDocumentBuilder();
doc=Db.parse(isp);
Element rootElem=doc.getDocumentElement();
NodeList itemlist=rootElem.getElementsByTagName("item");
Node currentitem=null;
Node childnode=null;
Node ContentChild=null;
Node CddatatChild=null;
NodeList childnodeList=null;
NodeList CddataList=null;
NodeList ContentChilList=null;
for(int i=0;i<itemlist.getLength();i++){
currentitem=itemlist.item(i);
childnodeList=currentitem.getChildNodes();
Log.v("dgd",currentitem.getNodeName());
for(int j=0;j<childnodeList.getLength();j++){
childnode=childnodeList.item(j);
if(childnode.getNodeName().equalsIgnoreCase("content:encoded")){
ContentChilList=childnode.getChildNodes();
ContentChilList.getLength();
CddatatChild=ContentChilList.item(0);
CddataList=CddatatChild.getChildNodes();
if(CddatatChild.getNodeName().equalsIgnoreCase("#cdata-section")){
output----> Log.v("dgd",CddatatChild.getTextContent());
}
}
}
}
Locat Output:
http://i.stack.imgur.com/zgHXz.png

Android search XML based on some condition

Here is what I am trying : I have a list of names. I want to search an XML file depending on that names.
XML looks like this :
<book>
<string> book name </string>
<array>
<string> Name1 </string>
<string> Name2 </string>
</array>
</book>
Now I want to search say "Name1" and if it matches I want to get the name of the book.
Is this possible? If yes can someone provide some code/snippet or maybe tell me the steps how I can do it. Thank you
Android has some built-in XML parsing functions. Take a look at http://developer.android.com/training/basics/network-ops/xml.html
Basically:
1) Set up an InputStream for the XML content (if you are downloading it, or reading it from a getResources() for example)
2) Set up your parser: XmlPullParser parser = Xml.newPullParser();
3) Start reading the XML in a loop. When parser.getName().equals("book"), then continue on until you get to your parser.getName().equals("string") and save the results of parser.getText(); Then when you continue on and hit parser.getName().equals("array") and you continue on again to parser.getName().equals("string"), then check the results of parser.getText() to see if it matches your search string.
Clear as mud?
Parsing XML is a lot harder than it was advertised to be 20 years ago or so, but once you understand that the parser reads the XML as it comes in, it makes it a little easier to see the overall picture of how to implement it. Study up on that link, it gives you everything you need to know.
There is a lot of ways to parse XML, I suggest you to use Jsoup
Its really easy to extract data from XML.
String html = "<?xml version=\"1.0\" encoding=\"UTF-8\">
<book>
<string> book name </string>
<array>
<string> Name1 </string>
<string> Name2 </string>
</array>
</book></xml>";
Document doc = Jsoup.parse(html, "", Parser.xmlParser());
Element book = doc.select("book").first();
Element bookName = book.getElementsByTag("string").first();
Elements array = book.getElementsByTag("array");
for (Element e : array.select("string")) {
//....
}
Thank you all for the answers. I am using the using the tutorial here and wrote this method to search the XML.
public List<String> search(String key, String url){
List<String> items = new ArrayList<String>();
XmlParser parser = new XmlParser();
String xml = parser.getXmlFromUrl(url); // getting XML
Document doc = parser.getDomElement(xml);
NodeList nl = doc.getElementsByTagName("book");
for(int i = 0; i<nl.getLength();i++){
Element e = (Element) nl.item(i);
NodeList n = e.getElementsByTagName("string");
if(parser.getElementValue(n.item(1)).equals(key) ||
parser.getElementValue(n.item(2)).equals(key) ){
items.add(parser.getElementValue(n.item(0)));
}
}
return items;
}

How to get Values in String Array from XML in android

I have a String value in a variable for eg ID
XML Like
<DocumentElement><Contact ID="1" Name="Test1" 1/><Contact ID="2" Name="TEST" /></DocumentElement>
i get my id in _s2
i want to add all id in a String Array like EmailArr
i have Done
Count=0;
EmailArr=new String[Count];
String _s2=event.getAttribute("ID").getValue();
if(_s2=="" || _s2==null){
_s2="N/A";
}
if(_s2!=null){
EmailArr[Count]=_s2;
Count=Count++;
}
I get Exception java.lang.ArrayIndexOutOfBoundsException
You need to create an Array with Xml Values:-
int count=XMlData.getPropertyCount();// Get the XML Data count/ some thing related to get Count of XMl Details
EmailArr=new String[Count]; // create Array EmailArr with that Count
You should give some initial size to your array :
EmailArr=new String[Count];//where count is number of records

submitting data to an array to be pulled later

So I've got the following:
NodeList nodeList = element.getElementsByTagName("rowset");
if (nodeList.getLength() > 0) {
for (int i = 0; i < nodeList.getLength(); i++) {
Element entry = (Element) nodeList.item(i);
Element _titleE = (Element) entry.getElementsByTagName("row").item(0);
Node _title = _titleE.getAttributes().getNamedItem("name");
t1.setText(_title.getNodeValue());
}
}
I've got the following XML layout:
<row name="" characterID="" corporationName="" corporationID="" />
(couple of lines of these)
the ideal way would be to create an array right? and then call the data from the array?
EDIT:
What I'm trying to do is read an XML File and store the values so that they can be accessed later so I'm assuming the ideal way would be to use an array?
(as my girlfriends name is jenny, too, I will be guessing what you want)
If you just want to store one value, an array or a ArrayList is good for that. If you need to store all 4 given attributes of your row, you should think about creating a class (lets call it MyRow) that contains those values. Than you can put all your rows into one ArrayList with the type of your class.
Pseudocode:
ArrayList<MyRow> myRowList = new ArrayList<MyRow>();
while reading each row
MyRow row = new MyRow();
row.mName = getAttributes().getNamesItem("name");
row.mCharacterId = getAttributes().getNamesItem("characterID");
// more setting...
}
A last tip for the next time: take some time to explain and specify your next question. That will improve the answers you get as well.

Categories

Resources