You need to sign in to do that
Don't have an account?
Help parsing xml and inserting its values into custom object
Hey Guys,
Im struggling abit with figuring out how to parse some xml into a custom object. Ive been working with the xmlstreamreader example, but I cant quite wrap my head around how step through the xml elements values that I want to insert into my custom object....
The xml response Im getting back from my webcallout looks like this:
<advertisers type="array"> <advertiser> <id type="integer">7</id> <name>ABC Telecom</name> </advertiser> <advertiser> <id type="integer">106</id> <name>ABC_Ozone</name> </advertiser><advertiser> <id type="integer">13</id> <name>Acme Corp</name> </advertiser> </advertisers>
My goal is loop through this and extract the value of id and name of each advertiser. I would then like to insert the id and name of each advertiser into a custom object. I would use the name field for the name of the advertiser and I have a custom field realationship setup to store the id value.
Any help is much appreciated.
Can't guarantee this is the most efficient way to do it, but using Account as an example, here's how you could parse that XML and create a list of Accounts to insert/upsert. I included the XML string so you can test it in the system console, but if you're getting it back from the web callout, you should be able to just set docx to the result and parse it from there...
All Answers
Can't guarantee this is the most efficient way to do it, but using Account as an example, here's how you could parse that XML and create a list of Accounts to insert/upsert. I included the XML string so you can test it in the system console, but if you're getting it back from the web callout, you should be able to just set docx to the result and parse it from there...
This was great help!
Thanks!!!
There's something odd with that XML - the nodes seem to be returned with text AND as null - not sure why to honest, but if you add a null check, it does work okay...
great work :-)
public with sharing class xmltosobject{
public string s='';
public void readxml(ID TestObjectID){
XmlParsed__c TObj = [SELECT XMl__c FROM XmlParsed__c where id= : TestObjectID];
s= TObj.Event_Message_XML__c ;
List<Account> newaccounts = new List<Account> ();
Dom.Document docx = new Dom.Document();
docx.load(s);
dom.XmlNode xroot = docx.getrootelement() ;
dom.XmlNode [] xrec = xroot.getchildelements() ; //Get all Record Elements
for(Dom.XMLNode child : xrec) //Loop Through Records
{
account a = new Account ();
for (dom.XmlNode awr : child.getchildren() ) {
if (awr.getname() == 'id') {
system.debug('Id' + awr.gettext());
a.accountnumber = awr.gettext();
}
if (awr.getname() == 'name') {
system.debug('name' + awr.gettext());
a.name = awr.gettext();
}
}
newaccounts.add(a);
}
system.debug(newaccounts);//you could insert here or upsert based on ID with an external Id field
}
}