Skip to content
This repository has been archived by the owner on Nov 1, 2024. It is now read-only.

Commit

Permalink
add an api example (#204)
Browse files Browse the repository at this point in the history
  • Loading branch information
devoncarew authored Feb 5, 2023
1 parent f118e00 commit 0b8025c
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 2 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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(
'<body>Hello world! <a href="www.html5rocks.com">HTML5 rocks!');
print(document.outerHtml);
Expand Down
57 changes: 57 additions & 0 deletions example/main.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import 'package:html/dom.dart';
import 'package:html/dom_parsing.dart';
import 'package:html/parser.dart';

void main(List<String> args) {
var document = parse('''
<body>
<h2>Header 1</h2>
<p>Text.</p>
<h2>Header 2</h2>
More text.
<br/>
</body>''');

// 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</${node.localName}>');
}
}

@override
void visitChildren(Node node) {
for (var child in node.nodes) {
visit(child);
}
}
}

0 comments on commit 0b8025c

Please sign in to comment.