简体   繁体   English

使用python / ElementTree和命名空间创建xml doc

[英]Creating xml doc with python/ElementTree and namespaces

I'm trying to create an in-memory xml document such that the root's child nodes all require a name space. 我正在尝试创建一个内存中的xml文档,以便root的子节点都需要一个名称空间。

The final document should look something like this: 最终文档看起来应该是这样的:

<Feed>            
<FeedEntity Id="0000" 
      xmlns="http://schemas.example.com/search/query/2010/5/revision">

    <FeedRequest locale="en-US" title="<some value>"/>
</FeedEntity>
... another FeedEntity element ...
</Feed>            

However, when I print out the document I've created with ElementTree lib, it looks more like this: 但是,当我打印出我使用ElementTree lib创建的文档时,它看起来更像是这样的:

<Feed>
    <ns0:FeedEntity Id="0000"
      xmlns:ns0="http://schemas.example.com/search/query/2010/5/revision">

        <FeedRequest locale="en-US" title="<some value>"/>
    </ns0:FeedEntity>
</Feed>

Here's how I'm creating the document: 这是我创建文档的方式:

counter = 0
namespace = "http://schemas.example.com/search/query/2010/5/revision"

root = Element("Feed")        

node_name = "{%s}FeedEntity" % (namespace, );                
feed_entity_element = Element(node_name)        

feed_entity_element["Id"] = "%04d" % (counter,);

feed_request_element = Element("FeedRequest");
feed_request_element["Culture"] = self.culture;
feed_request_element["Query"] = address;        

# append each of the elements to the xml document 
feed_entity_element.append(feed_request_element);

root.append(feed_entity_element);

str_data = ET.tostring(root)
print str_data

How do I get rid of the "ns0" parts in the final XML so it looks more like the first example noted above? 如何摆脱最终XML中的“ns0”部分,使其看起来更像上面提到的第一个例子?

With xml.etree , you cannot get the exact output as in the first example, but you can use the (global) register_namespace() function to use a "better" prefix than "ns0". 使用xml.etree ,您无法获得第一个示例中的确切输出,但您可以使用(global) register_namespace()函数使用“更好”的前缀而不是“ns0”。 For example: ET.register_namespace('rev', 'http://schemas.example.com/search/query/2010/5/revision') will make sure the output will look like rev:FeedEntity . 例如: ET.register_namespace('rev', 'http://schemas.example.com/search/query/2010/5/revision')将确保输出看起来像rev:FeedEntity

The (compatible) lxml library, however, is more flexible with regard to namespace prefixes, and allows you to provide a prefix mapping when creating an element . 然而,(兼容的) lxml库在名称空间前缀方面更灵活,并允许您在创建元素时提供前缀映射

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM