Output xml in python

How do I output an XML file using ElementTree in python?

I’m slightly confused about writing an xml file using the xml ElementTree module. I tried to build the document: e.g.

a = ET.Element('a') b = ET.SubElement(a, 'b') c = ET.SubElement(a, 'c') d = ET.SubElement(c, 'd') 

2 Answers 2

Create an instance of ElementTree class and call write() :

class xml.etree.ElementTree.ElementTree(element=None, file=None)

ElementTree wrapper class. This class represents an entire element hierarchy, and adds some extra support for serialization to and from standard XML.

element is the root element. The tree is initialized with the contents of the XML file if given.

tree = ET.ElementTree(a) tree.write("output.xml") 

Just to make sure I’m doing this correctly. If I wanted to attach a value or variable to a tag would it be: b.attrib = value , b.tag = variable?

You can write xml using ElementTree.write() function —

import xml.etree.ElementTree as ET a = ET.Element('a') b = ET.SubElement(a, 'b') c = ET.SubElement(a, 'c') d = ET.SubElement(c, 'd') ET.ElementTree(a).write("test.xml") 

This would write to file — test.xml —

To write xml with indents and elements on newline , you can use — xml.dom.minidom.toprettyxml . Example —

import xml.etree.ElementTree as ET import xml.dom.minidom as md a = ET.Element('a') b = ET.SubElement(a, 'b') c = ET.SubElement(a, 'c') d = ET.SubElement(c, 'd') xmlstr = ET.tostring(a).decode() newxml = md.parse(xmlstr) newxml = md.parseString(xmlstr) with open('test.xml','w') as outfile: outfile.write(newxml.toprettyxml(indent='\t',newl='\n')) 

Now, test.xml would look like —

Источник

How to stream XML output quickly from Python

What is a quick way of writing an XML file iteratively (i.e. without having the whole document in memory)? xml.sax.saxutils.XMLGenerator works but is slow, around 1MB/s on an I7 machine. Here is a test case.

2 Answers 2

I realize that this question has been asked awhile ago, but, in the mean time, an lxml API has been introduced that looks promising in terms of addressing the problem: http://lxml.de/api.html ; specifically, refer to the following section: «Incremental XML generation».

Читайте также:  Как запустить интерфейс в java

I quickly tested it by streaming a 10M file just as in your benchmark, and it took a fraction of a second on my old laptop, which is by no means very scientific, but is quite in the same ballpark as your generate_large_xml() function.

As Yury V. Zaytsev mentioned, lxml realy provides API for generating XML documents in streaming manner

from lxml import etree fname = "streamed.xml" with open(fname, "w") as f, etree.xmlfile(f) as xf: attribs = with xf.element("root", attribs): xf.write("root text\n") for i in xrange(10): rec = etree.Element("record", rec.text = "record text data" xf.write(rec) 

Resulting XML looks like this (the content reformatted from one-line XML doc):

 root text record text data record text data record text data record text data record text data record text data record text data record text data record text data record text data  

Источник

Reading and Writing XML Files in Python

Extensible Markup Language, commonly known as XML is a language designed specifically to be easy to interpret by both humans and computers altogether. The language defines a set of rules used to encode a document in a specific format. In this article, methods have been described to read and write XML files in python.

Note: In general, the process of reading the data from an XML file and analyzing its logical components is known as Parsing. Therefore, when we refer to reading a xml file we are referring to parsing the XML document.

In this article, we would take a look at two libraries that could be used for the purpose of xml parsing. They are:

Using BeautifulSoup alongside with lxml parser

For the purpose of reading and writing the xml file we would be using a Python library named BeautifulSoup. In order to install the library, type the following command into the terminal.

pip install beautifulsoup4

Beautiful Soup supports the HTML parser included in Python’s standard library, but it also supports a number of third-party Python parsers. One is the lxml parser (used for parsing XML/HTML documents). lxml could be installed by running the following command in the command processor of your Operating system:

Читайте также:  Php http digest auth

Firstly we will learn how to read from an XML file. We would also parse data stored in it. Later we would learn how to create an XML file and write data to it.

Reading Data From an XML File

There are two steps required to parse a xml file:-

XML File used:

Python3

Writing an XML File

Writing a xml file is a primitive process, reason for that being the fact that xml files aren’t encoded in a special way. Modifying sections of a xml document requires one to parse through it at first. In the below code we would modify some sections of the aforementioned xml document.

Python3

Using Elementtree

Elementtree module provides us with a plethora of tools for manipulating XML files. The best part about it being its inclusion in the standard Python’s built-in library. Therefore, one does not have to install any external modules for the purpose. Due to the xmlformat being an inherently hierarchical data format, it is a lot easier to represent it by a tree. The module provides ElementTree provides methods to represent whole XML document as a single tree.

In the later examples, we would take a look at discrete methods to read and write data to and from XML files.

Reading XML Files

To read an XML file using ElementTree, firstly, we import the ElementTree class found inside xml library, under the name ET (common convension). Then passed the filename of the xml file to the ElementTree.parse() method, to enable parsing of our xml file. Then got the root (parent tag) of our xml file using getroot(). Then displayed (printed) the root tag of our xml file (non-explicit way). Then displayed the attributes of the sub-tag of our parent tag using root[0].attrib. root[0] for the first tag of parent root and attrib for getting it’s attributes. Then we displayed the text enclosed within the 1st sub-tag of the 5th sub-tag of the tag root.

Читайте также:  Find numbers in list python

Python3

Writing XML Files

Now, we would take a look at some methods which could be used to write data on an xml document. In this example we would create a xml file from scratch.

To do the same, firstly, we create a root (parent) tag under the name of chess using the command ET.Element(‘chess’). All the tags would fall underneath this tag, i.e. once a root tag has been defined, other sub-elements could be created underneath it. Then we created a subtag/subelement named Opening inside the chess tag using the command ET.SubElement(). Then we created two more subtags which are underneath the tag Opening named E4 and D4. Then we added attributes to the E4 and D4 tags using set() which is a method found inside SubElement(), which is used to define attributes to a tag. Then we added text between the E4 and D4 tags using the attribute text found inside the SubElement function. In the end we converted the datatype of the contents we were creating from ‘xml.etree.ElementTree.Element’ to bytes object, using the command ET.tostring() (even though the function name is tostring() in certain implementations it converts the datatype to `bytes` rather than `str`). Finally, we flushed the data to a file named gameofsquares.xml which is a opened in `wb` mode to allow writing binary data to it. In the end, we saved the data to our file.

Источник

Оцените статью