1
我在本地文件中有XML,它是最終消息的模板,POST
被編輯爲REST
服務。該腳本預先處理模板數據,然後發佈。如何用BeautifulSoup替換/刪除XML標籤?
所以模板看起來是這樣的:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
<singleElement>
<subElementX>XYZ</subElementX>
</singleElement>
<repeatingElement id="11" name="Joe"/>
<repeatingElement id="12" name="Mary"/>
</root>
消息XML看起來應當是相同的不同之處在於repeatingElement
標籤需要用別的東西(基於屬性由腳本生成的XML被替換現有標籤)。
這裏是我的腳本至今:
xmlData = None
with open('conf//test1.xml', 'r') as xmlFile:
xmlData = xmlFile.read()
xmlSoup = BeautifulSoup(xmlData, 'html.parser')
repElemList = xmlSoup.find_all('repeatingelement')
for repElem in repElemList:
print("Processing repElem...")
repElemID = repElem.get('id')
repElemName = repElem.get('name')
# now I do something with repElemID and repElemName
# and no longer need it. I would like to replace it with <somenewtag/>
# and dump what is in the soup object back into a string.
# is it possible with BeautifulSoup?
我可以代替別的東西的重複元素,然後傾倒湯對象轉換成一個新的字符串,我可以張貼到我的REST API?
注意:我使用的是html.parser
,因爲我的can't get the xml parser to work但它工作正常,理解HTML比XML解析更寬鬆。
有趣的是,我只是想出了同樣的解決方案 – amphibient
不幸的是,我的系統(Win7)上運行的唯一一個湯姆分析器是'html.parser'(xml不工作,按照http://stackoverflow.com/問題/ 40640026/how-to-install-module-for-beautifulsoup-xml-parsing?noredirect = 1#comment68512605_40640026)將所有標記轉換爲小寫,我的REST API區分大小寫 – amphibient