9

In dart,

I want to parse a string "<!DOCTYPE HTMT><html><head></head><body>....</body></html>" to a DOM so that I can manipulate element in the generated DOM. I know in JQuery, there is $.parseHTML to deal with it. But I can not find anything similar in dart. Thank you.

(I have tried html2lib, but the output Document cannot use query(".classname") to select.)

xhg
  • 1,850
  • 2
  • 21
  • 35
  • 2
    I asked Vyacheslav Egorov on the twitter and he gave this answer: [https://api.dartlang.org/docs/channels/stable/latest/dart_html/DocumentFragment.html#html], DocumentFragment. – xhg Dec 18 '13 at 19:46

3 Answers3

6

You can create an element by parsing HTML text:

new Element.html("YOUR HTML STRING HERE");

see Dart: Up and Running CH03

EDIT
You may need to pass a NodeValidator to get the entire text rendered like:

NodeValidator nodeValidator = new NodeValidatorBuilder()
    ..allowTextElements();
    // ..allowHtml5()
    // ..allowElement('Button', attributes: ['ng-disabled']);

new Element.html("YOUR HTML STRING HERE", validator: nodeValidator);

If you run the application you get log messages like "element/attribute xxx removed from ..." if some of the text was not accepted by the NodeValidator.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
Eason PI
  • 293
  • 1
  • 3
  • 9
5

Try html. It's 100% pure Dart, so you should be set.

You could also consider an XML parser for Dart like xml depending on the nature of your HTML.

Jarl
  • 2,831
  • 4
  • 24
  • 31
Vidya
  • 29,932
  • 7
  • 42
  • 70
  • Thank you ,I tried, but the I can not use `query(".classname")` to select the element inside. – xhg Oct 19 '13 at 18:12
  • 1
    Maybe they never got around to compatibility with dart:html as they promised. Sorry. The easiest thing to do then might be just to use JQuery for the entire parse/manipulate process within your Dart application by using js-interop. https://www.dartlang.org/articles/js-dart-interop/ – Vidya Oct 19 '13 at 18:24
  • Maybe because it's still in beta version. Thank you ~ – xhg Oct 19 '13 at 18:47
  • By the way, I notice `dom = parse(string)`, what dart type is `dom`? – xhg Oct 19 '13 at 18:48
0

Check out this article in dart documentation

You can use this for dart

import 'dart:html';

and carryout parsing like this

querySelector('#theid').text = 'Wake up, sleepy head!';
}

In case of flutter, you have to add the "html" package in the pubspec.yaml below the cupertino_icons dependency like this for example

html: ^0.13.3+3

and then the dart file you have to import it like

import 'package:html/parser.dart' as parser;

and then carry out parsing as before but remember to add the alias name before each method!

Divakar Rajesh
  • 1,140
  • 2
  • 18
  • 23