Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

simple example of how to normalize and fix common errors in html #504

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions rcdom/examples/html_fixup.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// illustrates how to generate valid xhtml from html fragment with common errors

extern crate html5ever;
extern crate markup5ever_rcdom as rcdom;

use std::default::Default;

use html5ever::driver::ParseOpts;
use html5ever::tendril::{StrTendril, TendrilSink};
use html5ever::{parse_fragment, serialize, QualName};
use markup5ever::{local_name, namespace_url, ns};
use rcdom::{RcDom, SerializableHandle};

fn parse_and_serialize(input: StrTendril) -> StrTendril {
let dom = parse_fragment(
RcDom::default(),
ParseOpts::default(),
QualName::new(None, ns!(html), local_name!("body")),
vec![],
)
.one(input);
let inner: SerializableHandle = dom.document.children.borrow()[0].clone().into();

let mut result = vec![];
serialize(&mut result, &inner, Default::default()).unwrap();
StrTendril::try_from_byte_slice(&result).unwrap()
}

fn main() {
let sample_input = [
"<P>hello</P > ",
"http://example.com/page?query=1&foo=2",
"http://example.com/page?query=1&amp;foo=2",
"<p>foo",
];

println!("\n-- normalize html and fix common errors --\n");
sample_input.iter().for_each(|input_ref| {
let input = *input_ref;
let result = parse_and_serialize(input.into());
println!("input: {}", input);
println!("output: {}\n", result);
})
}