3 回答

TA貢獻(xiàn)1845條經(jīng)驗(yàn) 獲得超8個(gè)贊
下面(不使用任何外部庫(kù) - 只是核心 python)
import xml.etree.ElementTree as ET
root = ET.parse('input.xml')
head = root.find('.//head')
combined = ''.join(['<{}>{}</{}>'.format(e.tag,e.text,e.tag) for e in list(head)])
print(combined)
輸入.xml
<?xml version="1.0" encoding="UTF-8"?>
<data>
<head>
<version>1.0</version>
<project>hello, world</project>
<date>2020-08-15</date>
</head>
<file name="helloworld.py"/>
<file name="helloworld.ps1"/>
<file name="helloworld.bat"/>
</data>
輸出
<version>1.0</version><project>hello, world</project><date>2020-08-15</date>

TA貢獻(xiàn)1786條經(jīng)驗(yàn) 獲得超13個(gè)贊
如果您可以使用外部庫(kù),BeautifulSoup 在這方面做得很好。
https://www.crummy.com/software/BeautifulSoup/bs4/doc/#making-the-soup
這是您的文檔的示例。
from bs4 import BeautifulSoup as bs
xml_doc = """<?xml version="1.0" encoding="UTF-8"?>
<data>
<head>
<version>1.0</version>
<project>hello, world</project>
<date>2020-08-15</date>
</head>
<file name="helloworld.py"/>
<file name="helloworld.ps1"/>
<file name="helloworld.bat"/>
</data>"""
page_soup = bs(xml_doc)
page_soup.head.getText()
page_soup.head.getText().strip().replace('\n','').replace(' ','')
這將返回 head 標(biāo)簽的子標(biāo)簽的內(nèi)容,并去除換行符和空格。

TA貢獻(xiàn)1815條經(jīng)驗(yàn) 獲得超6個(gè)贊
每種方法都可能有問題。有的方法還會(huì)刪除有用的空格,有的方法在節(jié)點(diǎn)有屬性的時(shí)候就麻煩了。所以我會(huì)給你第三種方法。這也可能是一種不完美的方法:)
from simplified_scrapy import SimplifiedDoc,utils
# xml_doc = utils.getFileContent('myfile.xml')
xml_doc = """<?xml version="1.0" encoding="UTF-8"?>
<data>
<head>
<version>1.0</version>
<project>hello, world</project>
<date>2020-08-15</date>
</head>
<file name="helloworld.py"/>
<file name="helloworld.ps1"/>
<file name="helloworld.bat"/>
</data>"""
doc = SimplifiedDoc(xml_doc)
headXml = doc.head.html.strip() # Get internal data of head
print (doc.replaceReg(headXml,'>[\s]+<','><')) # Replace newlines and spaces with regex
結(jié)果:
<version>1.0</version><project>hello, world</project><date>2020-08-15</date>
添加回答
舉報(bào)