XML Parse Attribute

Questions, tips and tricks and techniques for scripting in Servoy

XML Parse Attribute

Postby bobcusick1332964082 » Thu Sep 12, 2013 7:52 pm

Hey folks - I'm accessing a web service that returns "funky" XML as the response:

Code: Select all
<result>
  <record>
    <field name="donor_id" id="donor_id" value="1"/>
    <field name="first_name" id="first_name" value="John D."/>
    <field name="last_name" id="last_name" value="McClurkin"/>
    <field name="middle_name" id="middle_name" value=""/>
  </record>
  <record>
    <field name="donor_id" id="donor_id" value="2"/>
    <field name="first_name" id="first_name" value="Bill"/>
    <field name="last_name" id="last_name" value="Jones"/>
    <field name="middle_name" id="middle_name" value=""/>
  </record>
</result>


That's literally all it returns. There is no default namespace.

So, I thought it would be a piece of cake parsing it using this:

Code: Select all
var str = plugins.http.getPageData("myLongURL")
  var myXML = new XML(str);
  var firstName = myXML.result.record.field.attribute("first_name").toString()


I know that I'm doing something stupid :D but everything I try just winds up with an empty string.

Then I tried:

Code: Select all
var firstName = myXML.result.record[0].field.attribute("first_name").toString()


But that just got an error:
Code: Select all
TypeError: Cannot read property \"field\" from undefined


I've already had a look at viewtopic.php?f=22&t=15818&p=85410 and I guess I'm just missing it.

Any pointers would be greatly appreciated!
bobcusick1332964082
 
Posts: 85
Joined: Wed Mar 28, 2012 9:48 pm

Re: XML Parse Attribute

Postby bobcusick1332964082 » Thu Sep 12, 2013 10:00 pm

UPDATE - ANSWERED

OK, after a lot of time and effort - I finally found the right syntax:

Code: Select all
myXML.record[0].field[1].attribute("value").toString()


I was trying to filter the FIELDS by the VALUE of the "name" property - rather than getting the ATTRIBUTE itself (e.g. "value" rather than "first_name").

Also, by explicitly calling specific records and fields (with the array notation), then getting the ATTRIBUTE "value" - bingo.
bobcusick1332964082
 
Posts: 85
Joined: Wed Mar 28, 2012 9:48 pm

Re: XML Parse Attribute

Postby ptalbot » Fri Sep 13, 2013 12:09 am

XML to be well formed, need a root Node. That root node is implied when you do new XML(string): your object becomes the root. And since you have more than one record and field nodes, they are XMLList (equivalent to arrays).
Patrick Talbot
Freelance - Open Source - Servoy Valued Professional
http://www.servoy-stuff.net
https://www.servoyforge.net
--------------------------------------------
Servoy 5.2.16 / 6.0.9 / 6.1.6 / 7.3.1
All OSes / Java 5 & 6 & 7
User avatar
ptalbot
 
Posts: 1616
Joined: Wed Mar 11, 2009 5:13 am
Location: Montreal, QC


Return to Methods

Who is online

Users browsing this forum: No registered users and 1 guest