2015-02-09 71 views
0

我目前使用amara 2进行XML工作,但是寻找可以与Py3和Py2一起工作的解决方案,我使用lxml.objectify取得了进展,但在如何生成此问题方面存在问题。如何使用lxml.objectify生成XML

<?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和这段代码我得到以下。

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> 

随着阿马拉我可以用这样的doc_header:

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>""" 

但使用我lxml.objectify我得到的属性上docO.querycreator错误。

我也用objectify.Elementmaker进行了实验,但无法使其工作。

+0

有点进一步,找到了tostring参数来获取xml声明,现在只需要命名空间的东西。 – Werner 2015-02-09 10:11:34

回答

0

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

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。

<?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>