parseHtmlFromAnything method

HtmlDocument parseHtmlFromAnything({
  1. required Window window,
  2. required String content,
  3. String mime = 'text/html',
})

Parses HtmlDocument.

If parseDocument actually returns XmlDocument (e.g. XHTML, SVG, etc.), converts it to HTML document.

Currently conversion happens by inserting the document element into the body of blank HTML document.

Implementation

HtmlDocument parseHtmlFromAnything({
  required Window window,
  required String content,
  String mime = 'text/html',
}) {
  final document = parseDocument(
    window: window,
    content: content,
    mime: mime,
  );
  if (document is HtmlDocument) {
    return document;
  }
  if (document is XmlDocument) {
    // Convert XML document to HTML document
    final htmlDocument = HtmlDocument.internal(
      window: window,
      contentType: mime,
      filled: false,
    );
    while (true) {
      final firstChild = document.firstChild;
      if (firstChild == null) {
        break;
      }
      if (firstChild is Element) {
        htmlDocument.append(firstChild);
      }
    }
    return htmlDocument;
  }
  throw StateError('Invalid document type');
}