首页 > 解决方案 > python lxml添加带有非法字符的项目名称

问题描述

我想使用 python 为 wordpress 构建 xml,

这是我当前的代码:

#!/usr/bin/python
import lxml.etree
import lxml.builder 
from lxml import etree   

E = lxml.builder.ElementMaker()
RSS = E.rss
channel = E.channel
ITEM = E.item
FIELD1 = E.field1
FIELD2 = E.field2
title = E.title
link = E.link
description = E.description
pubDate = E.pubDate
language = E.language

the_doc = RSS(
    channel(
        title("feed rss test by python"),
        link("https://localhost/"),
        description("description site"),
        pubDate("Mon, 23 Sep 2019 10:25:12 +0000"),
        language("en-US"),
    )
)

tmp = ITEM(
        title("title"),
        link("link"),
        pubDate("Mon, 23 Sep 2019 10:25:12 +0000"),
        description("test description"),
    )  

the_doc.append(RSS(channel(tmp)))

test = lxml.etree.tostring(the_doc, pretty_print=True, xml_declaration=True, encoding='UTF-16')

with open("data.xml", 'wb') as output:
    output.write(test)

代码正在运行,我的问题是我想wp:status在表 ITEM 中添加新项目,python 不允许使用以下声明变量:...我如何声明带有名称的 xml 项目wp:status

标签: pythonlxml

解决方案


如果我正确地回答了您的问题,您需要通过 xml.builder.ElementMaker 工厂创建一个名为“wp:status”的标签。

根据文档,这可以通过其他 apiE公开来完成:

E = lxml.builder.ElementMaker()
wp_status = E("wp:status")

tmp = ITEM(
    wp_status("cool status"),
     ...
)  

推荐阅读