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

Use misnested body attributes #35

Merged
merged 4 commits into from
Sep 20, 2020
Merged
Show file tree
Hide file tree
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
28 changes: 24 additions & 4 deletions src/soup.ml
Original file line number Diff line number Diff line change
Expand Up @@ -97,24 +97,44 @@ let create_document roots =

let create_soup () = create_document []

let from_signals signals =
let from_signals' ~map_attributes signals =
signals
|> (fun s -> Markup.trees
~text:(fun ss -> create_text (String.concat "" ss))
~element:(fun name attributes children ->
let attributes =
attributes |> List.map (fun ((_, n), v) -> n, v) in
attributes
|> List.map (fun ((_, n), v) -> n, v)
|> map_attributes name in
create_element (snd name) attributes children)
s)
|> Markup.to_list
|> create_document

let from_signals =
from_signals' ~map_attributes:(fun _n a -> a)

let parse text =
let body_attributes = ref [] in
let report _l e =
match e with
| `Misnested_tag ("body", _, attributes) ->
body_attributes := !body_attributes @ attributes
| _ -> () in
text
|> Markup.string
|> (fun s -> Markup.parse_html s)
|> (fun s -> Markup.parse_html ~report s)
|> Markup.signals
|> from_signals
|> from_signals'
~map_attributes:(fun name attributes ->
match name with
| ns, "body" when ns = Markup.Ns.html ->
List.fold_left (fun attributes (n, v) ->
match List.mem_assoc n attributes with
| true -> attributes
| false -> (n, v) :: attributes
) attributes !body_attributes
| _ -> attributes)

let is_document node =
match node.values with
Expand Down
8 changes: 8 additions & 0 deletions test/test.ml
Original file line number Diff line number Diff line change
Expand Up @@ -1097,6 +1097,14 @@ let suites = [
close_in channel;

assert_equal (parse contents $$ "li" |> count) 5);

("misnested-body-attributes" >:: fun _ ->
let document1 = "<html><body id='a'><img><body class='cls' id='b'>" in
let document2 = "<html><img><body class='cls' id='a'>" in
let document3 = "<html><body id='a' class='cls'><img>" in

assert_bool "equal" (equal (parse document1) (parse document2));
assert_bool "equal" (equal (parse document1) (parse document3)));
]
]

Expand Down