From 0b8025c16e1e5a5bcd451fb3a81cd98df218dcd4 Mon Sep 17 00:00:00 2001 From: Devon Carew Date: Sat, 4 Feb 2023 19:41:37 -0800 Subject: [PATCH] add an api example (#204) --- CHANGELOG.md | 1 + README.md | 4 ++-- example/main.dart | 57 +++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 60 insertions(+), 2 deletions(-) create mode 100644 example/main.dart diff --git a/CHANGELOG.md b/CHANGELOG.md index 2588fea..0e9440f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ - Adopted the `package:dart_flutter_team_lints` linting rules. - Fixed an issue with `querySelector` where it would fail in some cases with descendant or sibling combinators (#157). +- Add an API example in `example/`. ## 0.15.1 diff --git a/README.md b/README.md index f5388b2..05a19a8 100644 --- a/README.md +++ b/README.md @@ -9,9 +9,9 @@ A Dart implementation of an HTML5 parser. Parsing HTML is easy! ```dart -import 'package:html/parser.dart' show parse; +import 'package:html/parser.dart'; -main() { +void main() { var document = parse( 'Hello world! HTML5 rocks!'); print(document.outerHtml); diff --git a/example/main.dart b/example/main.dart new file mode 100644 index 0000000..309ed7c --- /dev/null +++ b/example/main.dart @@ -0,0 +1,57 @@ +import 'package:html/dom.dart'; +import 'package:html/dom_parsing.dart'; +import 'package:html/parser.dart'; + +void main(List args) { + var document = parse(''' + +

Header 1

+

Text.

+

Header 2

+ More text. +
+'''); + + // outerHtml output + print('outer html:'); + print(document.outerHtml); + + print(''); + + // visitor output + print('html visitor:'); + _Visitor().visit(document); +} + +// Note: this example visitor doesn't handle things like printing attributes and +// such. +class _Visitor extends TreeVisitor { + String indent = ''; + + @override + void visitText(Text node) { + if (node.data.trim().isNotEmpty) { + print('$indent${node.data.trim()}'); + } + } + + @override + void visitElement(Element node) { + if (isVoidElement(node.localName)) { + print('$indent<${node.localName}/>'); + } else { + print('$indent<${node.localName}>'); + indent += ' '; + visitChildren(node); + indent = indent.substring(0, indent.length - 2); + print('$indent'); + } + } + + @override + void visitChildren(Node node) { + for (var child in node.nodes) { + visit(child); + } + } +}