Reputation: 993
How can I create a SubElement of a Python ElementTree to write XML for this:
Hi What's up?
ie. where some text is bold and some isn't, but they both render on the same line when you print it out? I think this is what the XML should look like.
<p>
<b>Hi</b>
What's up?
</p>
I've tried several things, including the following:
import xml.etree.ElementTree as ET
p_element = ET.SubElement(section, "p")
bold = ET.SubElement(p_element, "b")
bold.text = "Hi"
not_bold = ET.SubElement(bold, "p")
not_bold.text = "What's up?"
That gives the following and it ends up all being bold:
<p>
<b>
Hi
<p>
What's up?
</p>
</b>
</p>
And if I instead do it like this:
import xml.etree.ElementTree as ET
p_element = ET.SubElement(section, "p")
bold = ET.SubElement(p_element, "b")
bold.text = "Hi"
not_bold = ET.SubElement(p_element, "p")
not_bold.text = "What's up?"
It gets the correct words in bold, but "Hi" and "What's up?" will render on different lines.
Upvotes: 0
Views: 1347
Reputation: 1300
You can do next:
import xml.etree.ElementTree as ET
p_element = ET.Element("p")
b_element = ET.SubElement(p_element, 'b')
b_element.text = "Hi"
b_element.tail = "What's up?"
print(ET.dump(p_element)) # <p><b>Hi</b>What's up?</p>
but don't use this module if you need to parse untrusted or unauthenticated data due to XML vulnerabilities.
Upvotes: 2