读取文件' /media/xml/example.xml'时出错::无法加载外部实体" /media/xml/example.xml"

时间:2015-10-08 09:18:51

标签: python xml django lxml

在我的Django项目中,我尝试加载外部xml文件并在其中查找一些数据。 但是我收到了一条错误消息。

Error reading file '/media/xml/example.xml': failed to load external entity "/media/xml/example.xml"

这是我的代码:

xml_file = etree.parse('/media/xml/example.xml')
find_data = etree.XPath("Some text")
data_result = find_data(xml_file)
你可以帮帮我吗?谢谢。

1 个答案:

答案 0 :(得分:1)

我建议你使用Beautifulsoup,它非常酷且使用方便:

dir = '/'.join([settings.BASE_DIR, 'media', 'xml/example.xml'])
abs_path = os.path.realpath(dir)
soup = BeautifulSoup(open(abs_path)) #<-- here you can now read/search thru xml file

for row in soup.find_all('row'):
    print row.find('name').text

如果你的xml看起来像:

<?xml version='1.0' encoding='us-ascii'?>
<root>
   <row>
     <name>Wake up to BeautifulSoup!</name>
   </row>
</root>

你会得到:

Wake up to BeautifulSoup!

文档为here