1

Does anyone have any idea on how to remove/add child nodes to an XML through apex code?

For example, i have an XML:

<?xml version="1.0" encoding="UTF-8"?>
<BookTitle>
<Book Title="1st Book"> Book1</Book >
<Book Title="2nd Book"> Book2</Book >
</BookTitle>

Here, i want to add/remove ' <Book Title="3r Book"> Book3</Book >' dynamically.

Any thoughts or helpful links will be helpful

1 Answer 1

2

A simple and safe way to manipulate XML in Apex is through the DOM implementation that is provided. (Trying to manipulate XML or JSON using string methods results in fragile code.)

This code illustrates how to use the DOM for your case:

@isTest
private class DomTest {

    @isTest
    static void test() {

        String xml = ''
                + '<?xml version="1.0" encoding="UTF-8"?>'
                + '<BookTitle>'
                + '<Book Title="1st Book"> Book1</Book >'
                + '<Book Title="2nd Book"> Book2</Book >'
                + '</BookTitle>'
                ;

        // Parses XML
        Dom.Document doc = new DOM.Document();
        doc.load(xml);

        // Remove an element
        for (Dom.XmlNode child : doc.getRootElement().getChildren()) {
            if (child.getAttribute('Title', null) == '2nd Book') {
                child.getParent().removeChild(child);
            }
        }

        // Add an element
        Dom.XmlNode addition = doc.getRootElement().addChildElement('Book', null, null);
        addition.setAttribute('Title', '3rd Book');
        addition.addTextNode('3rd Book');

        System.assertEquals(
                '<?xml version="1.0" encoding="UTF-8"?><BookTitle><Book Title="1st Book"> Book1</Book><Book Title="3rd Book">3rd Book</Book></BookTitle>',
                doc.toXmlString()
                );
    }
}
3
  • Thanks Keith C. Can u plz share on how to assign the updated XML value (either after adding/deleting) to a variable..
    – Rv1
    Jun 2, 2015 at 12:53
  • Your instructions will gives a boolean value whether true or false but it doesn't give updated value @Keith C
    – Rv1
    Jun 2, 2015 at 13:01
  • For the remove case the child variable is the removed XmlNode. For the add case addition us the added XmlNode.
    – Keith C
    Jun 4, 2015 at 8:01

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .