Parse XML Attributes in Apex

PHOTO EMBED

Mon Dec 05 2022 13:55:41 GMT+0000 (Coordinated Universal Time)

Saved by @Justus #apex

// 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();
}
content_copyCOPY