[SalesForce] How to parse XML data to JSON? How to deserialize XML to Apex class

I Have Xml data as Follows

String Data_XML = '<?xml version="1.0" encoding=""?> <book><price>100</price><Items>2</Items> </book>';

I wanted to deserialize XML to Apex class or JSON

Class Book{
    public Decimal price;
    public Integer Items;
}

Best Answer

There is no quick and easy way to transform XML either into JSON or into an Apex Class.

I came up against this in a recent project, and I ended up using the Dom.Document and Dom.XmlNode classes.

There's likely a way to abstract this pattern, but the basic idea that I used was to have an outer class to start the parsing, and then have a bunch of inner classes to represent the structure of the XML. It's effectively an implementation of a depth-first search algorithm

In your provided case, the solution is on the simple side

public class BookParser{
    List<Book> books;

    public BookParser(String xmlInput){
        books = new List<Book>();

        Dom.Document doc = new Dom.Document();
        doc.load(xmlInput);

        Book tempBook;
        for(Dom.XmlNode node :doc.getRootElement().getChildElements()){
            if(node.getName() == 'Book'){
                tempBook = new Book();
                tempBook.process(node);
                books.add(tempBook);
            }
        }
    }

    public class Book{
        Integer items;
        Decimal price;

        public void process(Dom.XmlNode inNode){
            for(Dom.XmlNode innerNode :inNode.getChildElements()){
                if(innerNode.getName() == 'Items'){
                    items = Integer.valueOf(innerNode.getText());
                } else if(innerNode.getName() ==  'price'){
                    price = Decimal.valueOf(innerNode.getText());
                }
            }
        }
   }
}

In general, each inner class that represents part of the XML data structure implements a process(Dom.XmlNode) method. The strengths of this pattern are that it limits the complexity of the process() method for each class, it doesn't care what order child nodes appear in, and it can parse the entire structure with a single call (here, it would be BookParser bp = new BookParser(inputXML);.