简体   繁体   English

XML 在 Python3 中创建文件

[英]XML create file in Python3

I ran into a problem and don't know how to solve it.我遇到了一个问题,不知道如何解决。
I have two types of objects, collection and element, they have many attributes and I need to write it to XML like a:我有两种类型的对象,集合和元素,它们有很多属性,我需要将其写入XML ,如下所示:

<data>
    <collection name="" .../>
        <element name="" link="" .../>
    </collection>
</data>

Every collection object has list with elements inside.每个集合 object 都有包含元素的列表。 So how can I do this with one loop that iterates over collections in a collection list.那么如何使用一个循环来遍历集合列表中的 collections 来做到这一点。

Thanks for your answers!感谢您的回答!

UPD: I just used formatted strings to write markup and this works great for such a simple task UPD:我只是使用格式化字符串来编写标记,这非常适合这样一个简单的任务

You can either use a library to handle that, but this might be a bit overkill.您可以使用库来处理它,但这可能有点矫枉过正。 If you want to give it a try, check out this official tutorial on the Python site: https://docs.python.org/3/library/xml.etree.elementtree.html If you want to give it a try, check out this official tutorial on the Python site: https://docs.python.org/3/library/xml.etree.elementtree.html

You could also give the elements you want to serialise a toXMLString() method, that generates the representation for this object in XML and returns it as a string.您还可以为要序列化的元素提供一个 toXMLString() 方法,该方法在 XML 中生成此 object 的表示并将其作为字符串返回。

Call this method in your loop, and write to your file.在您的循环中调用此方法,并写入您的文件。

Here's an example of using SimplifiedDoc.这是使用 SimplifiedDoc 的示例。 You need to install simplified_scrapy before you can use the following code.您需要先安装simple_scrapy,然后才能使用以下代码。 pip install simplified_scrapy pip 安装简化_scrapy

from simplified_scrapy import SimplifiedDoc, req, utils
html = '''
<data>
    <collection name="coll">
        <element name="ele1" link="link1" .../>
        <element name="ele2" link="link2" .../>
    </collection>
</data>
'''
doc = SimplifiedDoc(html)
elements = doc.data.collection.elements
print(elements.name)

Result:结果:

['ele1', 'ele2']

Here are more examples: https://github.com/yiyedata/simplified-scrapy-demo/tree/master/doc_examples这里有更多例子: https://github.com/yiyedata/simplified-scrapy-demo/tree/master/doc_examples

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

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