• Menghidupkan Mimpi ke Negeri Sakura

  • Follow me on Twitter

Writing XML in Python

The first step is to create our element:

# create the root <root>

root = ET.Elements (“root”)

After this code is executed, the variable root is an Element object, just like the Element objects that we used earlier to parse the XML.

The next step is to create the two child

if you know exactly what you are creating, it’s easiest to use the SubElement method, which creates an Element object that is a subelement (or child) of another Element object:

# create the first child <child>

child = ET.SubElements(root,“child”)

This will create a Element that is a child of root. We then need to set the text associated with that element. To do this we use the same text attribute that we used in the first parsing example. However, instead of simply reading the text attribute we set its value:

child.text = "gagus"
you can see may script as follows:
gagus@Rocks:~$ python
Python 2.6.4 (r264:75706, Dec  7 2009, 18:45:15)
[GCC 4.4.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from xml.etree import ElementTree as ET
>>> root = ET.Element('root')
>>> root
<Element root at b7713bac>
>>> child = ET.SubElement(root,'child')
>>> child.text = 'gagus'
>>> child
<Element child at b771688c>
>>> child = ET.SubElement(root,'child')
>>> child.text = 'ketut'
>>> child
<Element child at b766ab2c>
>>> print ET.tostring(root)
<root><child>gagus</child><child>ketut</child></root>

Tinggalkan Balasan

Isikan data di bawah atau klik salah satu ikon untuk log in:

Logo WordPress.com

You are commenting using your WordPress.com account. Logout / Ubah )

Gambar Twitter

You are commenting using your Twitter account. Logout / Ubah )

Foto Facebook

You are commenting using your Facebook account. Logout / Ubah )

Foto Google+

You are commenting using your Google+ account. Logout / Ubah )

Connecting to %s

%d blogger menyukai ini: