[SalesForce] Difficulty Parsing XML

I am having difficulty parsing the XML returned from a webservice callout. In the past, I've always been able to use XMLstreamreader, but it does not seem to work with formatting of the XML from this vendor (FedEx). Rather than having elements with attributes like this:

  <book title="Salesforce.com for Dummies"> -- where book is the element and title is the attribute

the XML has child objects who have child objects and so on. The above example would like this:

  <book>
    <title>Salesforce.com for Dummies</title>
  </book>

The actual XML is below (Fedex). I need to pull out the ServiceType and TotalNetCharge > Amount (note: there are other child objects using Amount as element name).

  <RateReplyDetails>
    <ServiceType>FIRST_OVERNIGHT</ServiceType>
    <RatedShipmentDetails>
      <ShipmentRateDetail>
        <TotalNetCharge>
          <Currency>USD</Currency>
          <Amount>55.61</Amount>
        </TotalNetCharge>
      </ShipmentRateDetail>
    </RatedShipmentDetails>
  </RateReplyDetails>

I've taken a look at parsing XML with the DOM parser, but can't seem to make the shift from documentation to returning the values. If someone could provide a real working example, I would be grateful.

Thanks,
KMT

Best Answer

This should help get you started:

String testxml = '<?xml version="1.0" encoding="UTF-8"?>' +
    '<RateReplyDetails>' +
    '<ServiceType>FIRST_OVERNIGHT</ServiceType>' +
    '<RatedShipmentDetails>' +
    '  <ShipmentRateDetail>' +
    '    <TotalNetCharge>' +
    '      <Currency>USD</Currency>' +
    '      <Amount>55.61</Amount>' +
    '    </TotalNetCharge>' +
    '  </ShipmentRateDetail>' +
    '</RatedShipmentDetails>' +
  ' </RateReplyDetails>';

     Dom.Document docx = new Dom.Document();
     docx.load(testxml);

dom.XmlNode xroot = docx.getrootelement() ;
String Service = xroot.getChildElement('ServiceType', null).getText();
system.debug(Service);

dom.XmlNode xrCharge = xroot.getChildElement('RatedShipmentDetails', null)
    .getChildElement('ShipmentRateDetail', null)
    .getChildElement('TotalNetCharge', null);

String sCurrency = xrCharge.getChildElement('Currency', null).gettext();
String sAmount = xrCharge.getChildElement('Amount', null).gettext();
system.debug(sCurrency + ':' + sAmount);
Related Topic