如何将lxml.objectify.ElementMaker与Sub / Data / Element混合使用

时间:2015-02-09 10:53:42

标签: lxml

我可以像这样使用EM:

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)

XML的内容是动态生成的,所以我希望能够按照这些方式进行,但是我得到了一个“没有这样的孩子”。 on' querycreator'当试图添加'名称' DataElement。令我困惑的是“查询工具”。在' docO'在我添加了' SubElement'之后。

myE = objectify.ElementMaker(namespace="http://www.vinoxml.org/XMLschema",
                             nsmap={None : "http://www.vinoxml.org/XMLschema"})

docO = myE.query()

qc = objectify.SubElement(docO, '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))

1 个答案:

答案 0 :(得分:0)

仅用于存档。我所有这一切的目标是从Amara 2转移到lxml。 我最终这样做了:

doc_header = """<query xmlns="http://www.vinoxml.org/XMLschema"></query>"""
nsVinoXML = u"{http://www.vinoxml.org/XMLschema}"

docO = objectify.fromstring(doc_header)

qc = objectify.SubElement(docO, nsVinoXML + u"querycreator")
qc.name = (u"The Wine Cellar Book - version %s"
           % 15.1)
qc.someint = 12
qc.somefloat = 21.2
qc.refcode = 1332322
qc.refcode.addattr('source', 'someone')

换句话说,只需要用“nsVinoXML”(即命名空间)作为前缀。

相关问题