首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Python中的LXML在孙辈节点之间插入

使用Python中的LXML在孙辈节点之间插入
EN

Stack Overflow用户
提问于 2014-10-19 14:06:41
回答 1查看 264关注 0票数 1

我正在尝试更新iTunes播客XML,并需要将信息放在第一个标记之上。我尝试过使用minidom和lxml.etree,但似乎无法深入到需要插入的地方。下面是我最近尝试过的XML和代码,这些错误是因为lxml将子节点转换成一个列表而导致错误。

代码语言:javascript
复制
<?xml version='1.0' encoding='UTF-8'?>
<rss xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" version="2.0">
   <channel>
    <title>Title</title>
    <link>weblink</link>
    <language>en-us</language>
    <copyright>Copyright</copyright>
    <itunes:subtitle>Subtitle</itunes:subtitle>
    <itunes:author>Author</itunes:author>
    <itunes:summary>Summary</itunes:summary>
    <description>Description</description>
    <itunes:owner>
        <itunes:name>Owner Name</itunes:name>
        <itunes:email>Owner email</itunes:email>
    </itunes:owner>
    <itunes:image image.jpg"/>
    <itunes:category text="MISC">
        <itunes:category text="MISC"/>
        </itunes:category> 
    <itunes:block>no</itunes:block>
    <itunes:explicit>no</itunes:explicit>

    <item>
        <title>First Entry</title>
        <itunes:author>Author</itunes:author>
        <itunes:subtitle>Just Another Entry</itunes:subtitle>
        <itunes:summary>Podcast Summary.</itunes:summary>
        <enclosure url="url_to_mp3" length="48412967" type="audio/mpeg"/>
        <guid>url_to_mp3</guid>
        <pubDate>Sun, 12 Oct 2014 12:00:00 -0500</pubDate>
        <itunes:duration>00:50:26</itunes:duration>
        <itunes:block>no</itunes:block>
        <itunes:explicit>no</itunes:explicit>
    </item>

我现在的代码是:

代码语言:javascript
复制
from lxml import etree

tree = etree.parse(file)
root = tree.getroot()
child = root.getchildren()
child.insert(13, etree.Element('item'))
child[13].insert(0, etree.SubElement(child[13], 'title'))

谢谢你能提供的任何帮助。

EN

回答 1

Stack Overflow用户

发布于 2014-10-20 02:41:42

这是我想出的答案。

代码语言:javascript
复制
from lxml import etree
parser = etree.XMLParser(remove_blank_text=True)
tree = etree.parse('file', parser)
root = tree.getroot()
child = root.find('channel')
new_item = etree.Element('item')
new_title = etree.SubElement(new_item, 'title')
new_title.text = "Test Title"
child.insert(13, new_item)
tree.write('file', pretty_print=True, xml_declaration=True, encoding='UTF-8')
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26451311

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档