我正在读取一个xml文件,并使用xmltodict和熊猫将其转换为df。
这就是文件中的元素之一的样子
<net>
<ref>https://whois.arin.net/rest/v1/net/NET-66-125-37-120-1</ref>
<endAddress>66.125.37.127</endAddress>
<handle>NET-66-125-37-120-1</handle>
<name>SBC066125037120020307</name>
<netBlocks>
<netBlock>
<cidrLenth>29</cidrLenth>
<endAddress>066.125.037.127</endAddress>
<type>S</type>
<startAddress>066.125.037.120</startAddress>
</netBlock>
</netBlocks>
<pocLinks/>
<orgHandle>C00285134</orgHandle>
<parentNetHandle>NET-66-120-0-0-1</parentNetHandle>
<registrationDate>2002-03-08T00:00:00-05:00</registrationDate>
<startAddress>66.125.37.120</startAddress>
<updateDate>2002-03-08T07:56:59-05:00</updateDate>
<version>4</version>
</net>由于有大量这样的记录正在被API提取,有时文件末尾的一些<net>对象可以部分下载。例句:一个标签没有结束标签。
这就是我为解析xml而写的。
xml_data = open('/Users/dgoswami/Downloads/net.xml', 'r').read() # Read data
xml_data = xmltodict.parse(xml_data,
process_namespaces=True,
namespaces={'http://www.arin.net/bulkwhois/core/v1':None})当这种情况发生时,我会得到一个类似的错误
no element found: line 30574438, column 37
我希望能够解析到最后一个有效的<net>元素。怎样才能做到呢?
发布于 2022-04-28 13:12:53
您可能需要事先修复xml -- xmltodict没有能力为您做这件事。
您可以利用lxml (如Python xml - handle unclosed token中所描述的)来修复您的xml:
from lxml import etree
def fixme(x):
p = etree.fromstring(x, parser = etree.XMLParser(recover=True))
return etree.tostring(p).decode("utf8")
fixed = fixme("""<start><net>
<endAddress>66.125.37.127</endAddress>
<handle>NET-66-125-37-120-1</handle>
</net><net>
<endAddress>66.125.37.227</endAddress>
<handle>NET-66-125-37-220-1</handle>
""")然后使用固定的xml:
import xmltodict
print(xmltodict.parse(fixed))要获得
OrderedDict([('start',
OrderedDict([('net', [
OrderedDict([('endAddress', '66.125.37.127'), ('handle', 'NET-66-125-37-120-1')]),
OrderedDict([('endAddress', '66.125.37.227'), ('handle', 'NET-66-125-37-220-1')])
])
]))
])https://stackoverflow.com/questions/72043695
复制相似问题