Adding a tag around a certain word in XML

Viewed 24

Let's say my xml looks like this:

<Dialog team="1">
<Participants>
<Person nickname="Leibniz"/>
<Person nickname="Clarke"/>
</Participants>
Leibniz-Clarke papers G. W. Leibniz and Samuel Clarke Clarke 1: (26.xi.1715)
<Body>
<Turn nickname="Leibniz" nr="1">
Leibniz's first paper (November 1715)
<Utterance genid="1" ref="-1"> 1 Natural religion seems to be greatly on the decline -in England-, where many people hold that human souls are made of matter, and others contend that God himself is a corporeal being, -i.e. a body-. </Utterance>
</Body>
</Dialog>

How can I add a tag like this around the word souls for example?

<Dialog team="1">
<Participants>
<Person nickname="Leibniz"/>
<Person nickname="Clarke"/>
</Participants>
Leibniz-Clarke papers G. W. Leibniz and Samuel Clarke Clarke 1: (26.xi.1715)
<Body>
<Turn nickname="Leibniz" nr="1">
Leibniz's first paper (November 1715)
<Utterance genid="1" ref="-1"> 1 Natural religion seems to be greatly on the decline -in England-, where many people hold that human <subject>souls</subject> are made of matter, and others contend that God himself is a corporeal being, -i.e. a body-. </Utterance>
</Body>
</Dialog>
1 Answers

Try:

from bs4 import BeautifulSoup


xml_doc = """
...your xml from the question...
"""

soup = BeautifulSoup(xml_doc, "xml")

for t in soup.find_all(text=True):
    if "souls" in t:
        t.replace_with(
            BeautifulSoup(
                t.replace("souls", "<subject>souls</subject>"), "html.parser"
            )
        )

print(soup)

Prints:

<?xml version="1.0" encoding="utf-8"?>
<Dialog team="1">
<Participants>
<Person nickname="Leibniz"/>
<Person nickname="Clarke"/>
</Participants>
Leibniz-Clarke papers G. W. Leibniz and Samuel Clarke Clarke 1: (26.xi.1715)
<Body>
<Turn nickname="Leibniz" nr="1">
Leibniz's first paper (November 1715)
<Utterance genid="1" ref="-1"> 1 Natural religion seems to be greatly on the decline -in England-, where many people hold that human <subject>souls</subject> are made of matter, and others contend that God himself is a corporeal being, -i.e. a body-. </Utterance>
</Turn>
</Body></Dialog>
Related