Python 如何在树中插入新块?
使用Beautifulsoup,我需要读取一个KML文件,并在包含LineString部分的所有Placemark中插入一个新块 以下是KML文件:Python 如何在树中插入新块?,python,xml,beautifulsoup,Python,Xml,Beautifulsoup,使用Beautifulsoup,我需要读取一个KML文件,并在包含LineString部分的所有Placemark中插入一个新块 以下是KML文件: <?xml version="1.0" encoding="utf-8"?> <kml xmlns="http://www.opengis.net/kml/2.2"> <Document> <name>Document.kml&l
<?xml version="1.0" encoding="utf-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
<Document>
<name>Document.kml</name>
<Placemark>
<name>My track</name>
<LineString>
<coordinates>-0.376291,43.296237,199.75
-0.377381,43.29405</coordinates>
</LineString>
</Placemark>
</Document>
</kml>
以下操作不起作用:
from bs4 import BeautifulSoup as Soup
with open('input.kml') as data:
kml_soup = Soup(data, 'lxml-xml') # Parse as XML
placemarks = kml_soup.find_all('Placemark')
for pm in placemarks:
if pm.find('LineString'):
print("LS found")
#How to insert new elements before LineString?
#<Style><LineStyle><width>3</width></LineStyle></Style>
style = kml_soup.new_tag("Style")
style.string = "<LineStyle><width>3</width></LineStyle>"
#AttributeError: 'NoneType' object has no attribute 'insert_before'
pm.string.insert_before(style)
谢谢。您可能使用了错误的对象。尝试以下方法
placemarks = kml_soup.find_all('Placemark')
for pm in placemarks:
LineString = pm.find('LineString')
if LineString:
print("LS found")
style = kml_soup.new_tag("Style")
style.string = "<LineStyle><width>3</width></LineStyle>"
LineString.insert_before(style) # Use LineString
这是另一个解决方案
from simplified_scrapy import SimplifiedDoc,utils
html = utils.getFileContent('input.kml')
doc = SimplifiedDoc(html)
placemarks = doc.selects('Placemark')
for pm in placemarks:
LineString = pm.select('LineString')
if LineString:
print("LS found")
style = "<Style><LineStyle><width>3</width></LineStyle></Style>\n"+" "*6
LineString.insertBefore(style)
# print (doc.html)
谢谢,就这样。