Activity Forums Salesforce® Discussions How to parse XML String in Salesforce Apex Class?

  • Aman

    Member
    May 31, 2018 at 7:49 am

    Hi Parv,

    As per your requirement,you can take the following string as reference
    XMLString = '<?xml version="1.0" encoding="UTF-8"?><products><product><name>Xbox</name><code>XBO</code></product><product><name>Playstation</name><code>PS</code></product><product><name>Wii</name></product></products>';
    You need to pass this String in the given Method.

    public XMLparse(String XMLString){

    pro = new list<Product2>();

    DOM.Document doc=new DOM.Document();

    try{

    doc.load(XMLString);

    DOM.XmlNode rootNode=doc.getRootElement();

    parseXML(rootNode);

    pro.add(temppro);

    insert pro;

    }catch(exception e){

    system.debug(e.getMessage());

    }

    }

     

    private void parseXML(DOM.XMLNode node) {

    if (node.getNodeType() == DOM.XMLNodeType.ELEMENT) {

    if(node.getName()=='product'){

    if(temppro!=null)

    pro.add(temppro);

    temppro = new product2();

    }

    if(node.getName()=='name')

    temppro.name=node.getText().trim();

    if(node.getName()=='code')

    temppro.productcode=node.getText().trim();

    }

    for (Dom.XMLNode child: node.getChildElements()) {

    parseXML(child);

    }

    }

    Thanks

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos