BrT
BrT

Reputation: 629

Empty element error with Beautiful Soup

I am parsing an xml file using Beautiful Soup but have found inconsistent behaviour when parsing empty elements. I.e.

from BeautifulSoup import BeautifulSoup
s1 = "<c><a /><b /></c>"
s2 = "<c><a></a><b></b></c>"
soup1 = BeautifulSoup(s1)
soup2 = BeautifulSoup(s2)
print soup1
# <c><a><b></b></a></c>
print soup2
# <c><a></a><b></b></c>

Note that the b tag is inside the a tag in the first case, but not in the second. I thought that the XML spec meant that s1 and s2 were equivalent?

Any thoughts as to how I can deal with this?

Upvotes: 2

Views: 813

Answers (1)

orlp
orlp

Reputation: 117641

The anchor and bold (<a>, <b>) elements can not be self-closed, so this is invalid XHTML.

On top of that, the XHTML spec says a space must lead the slash:

Include a space before the trailing / and > of empty elements, e.g. <br />, <hr /> and <img src="karen.jpg" alt="Karen" />. Also, use the minimized tag syntax for empty elements, e.g. <br />, as the alternative syntax <br></br> allowed by XML gives uncertain results in many existing user agents.

Upvotes: 1

Related Questions