I'm trying to parse an HTML string. This string comes from a Salesforce rich text editor's content. It's a field saved on a record.

String html = '<p>hello<br>goodbye</p>'

String XML_DECLARATION = '<?xml version="1.0" encoding="utf-8"?>';
Dom.Document document = new Dom.Document();
document.load(XML_DECLARATION + html);

This raises the error:

ERROR: System.XmlException: Failed to parse XML due to: end tag name </p> must match start tag name <br> from line 1

This appears to be because this string is treated as "xhtml+xml" or maybe just "xml" content type, despite the class name being Dom.Document. It's expecitng the <br> tag to have a paired closing tag, or be self closing.

I can do a find and replace on these, but I'm worried about other self closing tags. Is there a way to make the parser handle non-self-closing <br> tags without erroring?

I've tried wrapping the string in <!DOCTYPE HTML><html xmlns="http://www.w3.org/1999/xhtml">...</html> but that didn't have an effect.

1 Answer 1


Dom.Document, despite its namespace, is an XML parser. It is not meant to handle <br>, because XML doesn't allow it. You will need to find/replace all <br> with <br/>. Self-closing tags are just fine, e.g. <hr/>, as well as tags that are simply empty of content (<p/>).

  • Makes sense, and creates a chicken and egg problem of trying to parse xml before using it. For now i'm going to use html.replaceAll('<(hr|br)\\s?>', '<$1 />'));
    – Andy Ray
    Aug 7, 2020 at 18:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.