Parsing XML struct
I am seeking some help on parsing xml returned from an xmlrpc call.
An example result is a structure of name/value pairs:
<methodResponse>
<params>
<param>
<value><array>
<data>
<value><struct>
<member><name>id</name>
<value><string>8</string></value>
</member>
<member><name>name</name>
<value><string>Dr Bar</string></value>
</member>
</struct></value>
</data>
</array></value>
</param>
</params>
</methodResponse>
I have tired the following but get null so I suppose I am over simplifying.
var result = this.responseText;
Titanium.API.info('Received: '+result);
var xml = Ti.XML.parseString(result);
var structList = xml.documentElement.getElementsByTagName("struct");
Titanium.API.info(structList.length);
Titanium.API.info(structList.item(0).getElementsByTagName("name").text);
Titanium.API.info(structList.item(0).getElementsByTagName("value").text);
correction.
Titanium.API.info(structList.item(0).getElementsByTagName("name").item(0).text);
Does give me "id" but
Titanium.API.info(structList.item(0).getElementsByTagName("value").item(0).text);
Gives me zip.
Ok, correction again..
Titanium.API.info(structList.item(0).getElementsByTagName("value").item(0).getElementsByTagName("string").item(0).text);
Gives me "8".
I just need a more efficient way to do this as the structures returned by various calls are not all the same.
Ok, now I am this far I can figure it out.
New question: how do you delete a dumb question so it does not clutter up the Q&A?
Thanks.
4 Answers
-
Here's a solution:
var result = this.responseText; var xml = Ti.XML.parseString(result); var params = xml.documentElement.getElementsByTagName("member"); var name = xml.documentElement.getElementsByTagName("name"); var value = xml.documentElement.getElementsByTagName("string"); var data = []; for (var i=0;i<params.item.length;i++) { Ti.API.log('Param '+i+': Name: '+n.item(i).text); Ti.API.log('Param '+i+': Value: '+v.item(i).text); // Add to array data.push({"name":n.item(i).text,"value":v.item(i).text}); }
Your XML doc could have a better structure, which would make it easier to parse. Here's a screenshot.
If you use
responseXML
, your XML needs to be validated (ie, DTD). -
One thing you can do is to also try using :
var xml = this.responseXML;
Instead of using Ti.XML.parseString from the result.
-
This isnt a dumb post - it got me over my brain block with xml in this environment!
-
I have an XML with this structure:
<?xml version="1.0" encoding="UTF-8"?> <Result> <User> <ID>65</ID> <Name>adm_adm</Name> <Email>noreply@domain.com</Email> </User> <Accounts> <Account ID="248" Name="wertyu" /> <Account ID="251" Name="hgdfh" /> <Account ID="249" Name="wertyui" /> </Accounts> <Roles> <Rol ID="14" Name="SentDocsAsign" /> <Rol ID="15" Name="RcvDocsAsign" /> <Rol ID="30" Name="SenderUser" /> </Roles> </Result>
I parsed all the User data, but how can i parse the Accounts and the Roles nodes?