使用命名空间python3解析XML属性

时间:2017-11-21 04:05:37

标签: python-3.x xml-parsing

我查看了Parsing XML with namespace in Python via 'ElementTree'上的另一个问题,并查看了xml.etree.ElementTree文档。我承认的问题是相似的,所以请随意将其标记为重复,但我无法弄明白。

我遇到问题的代码行是

instance_alink = root.find('{http://www.w3.org/2005/Atom}link')

我的代码如下:

import xml.etree.cElementTree as ET

tree = ET.parse('../../external_data/rss.xml')
root = tree.getroot()

instance_title = root.find('channel/title').text
instance_link = root.find('channel/link').text
instance_alink = root.find('{http://www.w3.org/2005/Atom}link')
instance_description = root.find('channel/description').text
instance_language = root.find('channel/language').text
instance_pubDate = root.find('channel/pubDate').text
instance_lastBuildDate = root.find('channel/lastBuildDate').text

XML文件:

<?xml version="1.0" encoding="windows-1252"?>
<rss version="2.0">
  <channel>
    <title>Filings containing financial statements tagged using the US GAAP or IFRS taxonomies.</title>
    <link>http://www.example.com</link>
    <atom:link href="http://www.example.com" rel="self" type="application/rss+xml" xmlns:atom="http://www.w3.org/2005/Atom"/>
    <description>This is a list of up to 200 of the latest filings containing financial statements tagged using the US GAAP or IFRS taxonomies, updated every 10 minutes.</description>
    <language>en-us</language>
    <pubDate>Mon, 20 Nov 2017 20:20:45 EST</pubDate>
    <lastBuildDate>Mon, 20 Nov 2017 20:20:45 EST</lastBuildDate>
....

我试图检索的属性在第6行;所以&#39; href&#39;,&#39;输入&#39;等等。

<atom:link href="http://www.example.com" rel="self" type="application/rss+xml" xmlns:atom="http://www.w3.org/2005/Atom"/>

显然,我已经尝试了

instance_alink = root.find('{http://www.w3.org/2005/Atom}link').attrib

但这不起作用,因为它的类型为无。我的想法是,它正在寻找孩子,但没有。我可以在XML中抓取其他行中的属性,但出于某种原因不能这些。我也玩过ElementTree和lxml(但无论出于何种原因,lxml都无法在Windows上正常加载)

非常感谢任何帮助,因为文档似乎很少。

1 个答案:

答案 0 :(得分:0)

我能够用

解决
{http://www.w3.org/2005/Atom}link

问题在于我在<channel>的同一级别寻找标记@Multipart @POST(ApiURLs.EDIT_USER_PROFILE) Call<EditProfileModel> EditUserProfile (@Part("user_id) String userId , @Part("user_name") String userName , @Part("language_id") String languageId , @Part("state_id") String stateId , @Part MultipartBody.Part profilePicture); ,当然,这个标记不存在。