[英]How to determine what the root tag name is for a XML document
我想知道如何使用xml.dom.minidom
確定XML文檔的根標簽。
<?xml version="1.0" encoding="UTF-8"?>
<root>
<child1></child1>
<child2></child2>
<child3></child3>
</root>
在上面的示例XML中,我的根標簽可能是3或4種不同的東西。 我要做的就是拉標簽,然后使用該值通過標簽名稱獲取元素。
def import_from_XML(self, file_name)
file = open(file_name)
document = file.read()
if re.compile('^<\?xml').match(document):
xml = parseString(document)
root = '' # <-- THIS IS WHERE IM STUCK
elements = xml.getElementsByTagName(root)
我嘗試在xml.dom.minidom
的文檔中進行xml.dom.minidom
,但是,這讓我xml.dom.minidom
,而且找不到任何可以完全回答此問題的東西。
我正在使用Python 3.6.x,並且如果可能的話,我希望保留標准庫。
對於您注釋為Where I am stuck
的那一行,以下代碼應將XML文檔的根標記的值分配給變量theNameOfTheRootElement
:
theNameOfTheRootElement = xml.documentElement.tagName
這是我上次處理xml時所做的。 我沒有使用您使用的方法,但希望它能對您有所幫助。
import urllib2
from xml.etree import ElementTree as ET
req = urllib2.Request(site)
file=None
try:
file = urllib2.urlopen(req)
except urllib2.URLError as e:
print e.reason
data = file.read()
file.close()
root = ET.fromstring(data)
print("root", root)
for child in root.findall('parent element'):
print(child.text, child.attrib)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.