首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用lxml.objectify生成XML

如何使用lxml.objectify生成XML
EN

Stack Overflow用户
提问于 2015-02-09 17:41:03
回答 1查看 315关注 0票数 0

我目前正在使用Amara2进行XML工作,但是为了寻找一个可以与Py3和Py2一起工作的解决方案,我在lxml.objectify上取得了一些进展,但是在如何生成它方面有一个问题。

代码语言:javascript
复制
<?xml version="1.0" encoding="UTF-8"?>
<query xmlns="http://www.vinoxml.org/XMLschema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"/>
<querycreator>
  <name>The Wine Cellar Book - version 15.1</name>
</querycreator>

使用lxml和下面的代码片段,我可以得到以下结果。

代码语言:javascript
复制
doc_header = """<query></query>"""

doc = etree.ElementTree(etree.fromstring(doc_header))
docO = objectify.fromstring(doc_header)

objectify.SubElement(docO, "querycreator")
docO.querycreator.name = objectify.DataElement(u"The Wine Cellar Book - version %s"
                                               % 15.1)


<query>
  <querycreator>
    <name>The Wine Cellar Book - version 15.1</name>
  </querycreator>
</query>

在amara中,我可以使用这样的doc_header:

代码语言:javascript
复制
doc_header = """<query xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.vinoxml.org/XMLschema" xmlns:xsd="http://www.w3.org/2001/XMLSchema"></query>"""

但是在docO.querycreator上使用I和lxml.objectify时,我得到了属性错误。

我也尝试过objectify.Elementmaker,但也不能让它工作。

EN

回答 1

Stack Overflow用户

发布于 2015-02-09 18:43:40

通过使用ElementMaker,我得到了名称空间。

代码语言:javascript
复制
myE = objectify.ElementMaker(namespace="http://www.vinoxml.org/XMLschema",
                             nsmap={None : "http://www.vinoxml.org/XMLschema"})

docO = myE.query(myE.querycreator())

docO.querycreator.name = objectify.DataElement(u"The Wine Cellar Book - version %s"
                                               % 15.1)

objectify.deannotate(docO)
etree.cleanup_namespaces(docO)
print(etree.tostring(docO, pretty_print=True,
                     encoding="UTF-8", xml_declaration=True))

我得到了vinoXML名称空间,但不确定是否需要:xsi和:xsd。

代码语言:javascript
复制
<?xml version='1.0' encoding='UTF-8'?>
<query xmlns="http://www.vinoxml.org/XMLschema">
  <querycreator>
    <name>The Wine Cellar Book - version 15.1</name>
  </querycreator>
</query>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28406675

复制
相关文章

相似问题

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