+ Start a Discussion
Baz DensonBaz Denson 

Extract parameter data from XML

I have some XML to parse which contains things like this
 
<ns0:DisplacementMeasure unitCode="cubic centimeter">976</ns0:DisplacementMeasure>

Now, I can easily access the '976' value for the displacement measure using getText(), but I also need to store the 'cubit centimeter' as the displaement measure unit.

Can anyone advise how to extract this please?

Best Answer chosen by Baz Denson
Alain CabonAlain Cabon
Hi Baz,
 
system.debug('start...');
String xmlstring= '<root xmlns:ns0="http://tempuri.org"><ns0:DisplacementMeasure unitCode="cubic centimeter">976</ns0:DisplacementMeasure></root>';
DOM.Document xmlDOC = new DOM.Document();
xmlDOC.load(xmlstring);
String namespace = 'http://tempuri.org';
DOM.XMLNode rootElement = xmlDOC.getRootElement();
system.debug('root:' + rootElement);
dom.XmlNode DisplacementMeasure = rootElement.getChildElement('DisplacementMeasure', namespace);
system.debug('DisplacementMeasure unitCode:' + DisplacementMeasure.getAttribute('unitCode',null));
system.debug('DisplacementMeasure text:' + DisplacementMeasure.getText());
system.debug('end...');

User-added image

 

All Answers

Alain CabonAlain Cabon
Hi Baz,
 
system.debug('start...');
String xmlstring= '<root xmlns:ns0="http://tempuri.org"><ns0:DisplacementMeasure unitCode="cubic centimeter">976</ns0:DisplacementMeasure></root>';
DOM.Document xmlDOC = new DOM.Document();
xmlDOC.load(xmlstring);
String namespace = 'http://tempuri.org';
DOM.XMLNode rootElement = xmlDOC.getRootElement();
system.debug('root:' + rootElement);
dom.XmlNode DisplacementMeasure = rootElement.getChildElement('DisplacementMeasure', namespace);
system.debug('DisplacementMeasure unitCode:' + DisplacementMeasure.getAttribute('unitCode',null));
system.debug('DisplacementMeasure text:' + DisplacementMeasure.getText());
system.debug('end...');

User-added image

 
This was selected as the best answer
Alain CabonAlain Cabon
I don't know where is your XML element so you can need a Xpath expression.

https://developer.salesforce.com/forums/?id=9060G000000XjHDQA0
 
Baz DensonBaz Denson
Thanks Alan.. I had alreay solved it in exactly the same way!
Alain CabonAlain Cabon
Ok, at least, the solution could help other people because there is always this complication with the namespace at first.
Best regards
Alain