// String or webservice response
String xmlString = '<Books><Book author="J.K. Rowling" title="Harry Potter and the philosopher\'s stone"/><Book author="Stephen King" title="Carry"/></Books>';
// Create a XSR
XmlStreamReader reader = new XmlStreamReader(xmlString);
while(reader.hasNext()) {
switch on reader.getEventType() {
// Attributes only occur on start elements
when START_ELEMENT{
// Check for your required property
if (reader.getLocalName() =='Book') {
// Iterate all the atttributes in the Book tag
for(Integer i=0, attrCount=reader.getAttributeCount(); i<attrCount; i++){
// "Verbosed" for a more clear explanation
String attrName = reader.getAttributeLocalName(i);
String attrValue= reader.getAttributeValue(null,attrName);
// Get the attribute + value
System.debug(attrName + ' :: ' + attrValue);
}
}
}
}
reader.next();
}
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter