initial
This commit is contained in:
commit
74ae93a96e
1 changed files with 94691 additions and 0 deletions
46
_resources/parsing_with_new.dart
Normal file
46
_resources/parsing_with_new.dart
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
import 'package:html/parser.dart' as html_parser; // To parse the HTML
|
||||
import 'package:html/dom.dart'; // For working with the DOM structure
|
||||
|
||||
void main() {
|
||||
// Example HTML content with some nested tags
|
||||
String htmlContent = '''
|
||||
<div>
|
||||
Line 1<br>
|
||||
<div>Line 2<br>Line 3<br><span>Nested Line 4</span></div>
|
||||
Line 5
|
||||
</div>
|
||||
''';
|
||||
|
||||
// Parse the HTML content
|
||||
Document document = html_parser.parse(htmlContent);
|
||||
|
||||
// Find the desired element
|
||||
Element? divElement = document.querySelector('div');
|
||||
|
||||
if (divElement != null) {
|
||||
// Extract and preserve newlines recursively
|
||||
String preservedText = preserveTextWithNewlines(divElement);
|
||||
print(preservedText);
|
||||
}
|
||||
}
|
||||
|
||||
String preserveTextWithNewlines(Element element) {
|
||||
final buffer = StringBuffer();
|
||||
|
||||
for (var node in element.nodes) {
|
||||
if (node is Text) {
|
||||
// Append text content
|
||||
buffer.write(node.text);
|
||||
} else if (node is Element) {
|
||||
if (node.localName == 'br') {
|
||||
// Add newline for <br> tags
|
||||
buffer.write('\n');
|
||||
} else {
|
||||
// Recursively process child elements
|
||||
buffer.write(preserveTextWithNewlines(node));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return buffer.toString();
|
||||
}
|
||||
Loading…
Reference in a new issue