4 ms·
The big problem with the content is suggesting to use an XML parser to parse HTML. That might often work, and several XML parsers have some sort of HTML "mode",
by gnud 7y ago
The big problem with the content is suggesting to use an XML parser to parse HTML. That might often work, and several XML parsers have some sort of HTML "mode", but in general, no, not really.
HTML documents are frequently invalid XML.
HTML documents lack an XML declaration, they don't close all tags, etc. They might even lack a root element. Someone mentioned this in a comment on SO, but it was (as far as I could see) not really addressed or answered.
HTML 5 has it's own parsing rules, specified at [1].
However, I don't know of any implementation of these outside of browsers. I normally use Beatuiful Soup [2] (for Python) or HTML Agility Pack [3] (for .NET), and while I don't think these implement the exact standard, they're easier than struggling with a XML parser for HTML "in the wild".
1: https://html.spec.whatwg.org/multipage/parsing.html https://html.spec.whatwg.org/multipage/parsing.html
2: https://www.crummy.com/software/BeautifulSoup/ https://www.crummy.com/software/BeautifulSoup/
3: https://html-agility-pack.net/ https://html-agility-pack.net/
- kortex 7y agoThe question title implies he's parsing XHTML text. > XHTML is an XML-based HTML. It serves the same function as HTML, but with the same rules as XML documents. https://stackoverflow.com/q/1429065 https://stackoverflow.com/q/1429065
- ChrisSD 7y agoThe question title is ambiguous but the question tags include both HTML and XHTML. Self-closing `<element />` is an XML-ism which in HTML is treated the same as `<element>` but it was still fashionable to use them in HTML when XHTML was at its height.