Skip to content

Instantly share code, notes, and snippets.

@dketov
Created December 14, 2011 16:15
Show Gist options
  • Select an option

  • Save dketov/1477214 to your computer and use it in GitHub Desktop.

Select an option

Save dketov/1477214 to your computer and use it in GitHub Desktop.
Работа с форматом XML
# -*- encoding: utf-8 -*-
"""
Разбор XML формата
"""
from xml.dom.minidom import parse, parseString
dom1 = parse( "example.xml" ) # parse an XML file
dom2 = parseString( "<myxml>Some data <empty/> some more data</myxml>" )
print dom1.toxml()
print dom2.toxml()
# -*- encoding: utf-8 -*-
"""
Поиск элемента
"""
from xml.dom.minidom import parse
dom = parse("example.xml")
for node in dom.getElementsByTagName('configuration'):
print node.toxml()
# -*- encoding: utf-8 -*-
"""
Добавление элемента
"""
from xml.dom.minidom import parse
dom = parse("example.xml")
x = dom.createElement("device") # creates <foo />
dom.childNodes[0].appendChild(x) # appends at end of 1st child's children
print dom.toxml()
# -*- encoding: utf-8 -*-
"""
Добавление узла
"""
from xml.dom.minidom import parse
dom = parse("example.xml")
device = dom.createElement("device")
description = dom.createElement("description")
type = dom.createElement("type")
txt = dom.createTextNode("server")
dom.childNodes[1].appendChild(device)
device.appendChild(description)
description.appendChild(type)
type.appendChild(txt)
print dom.toxml()
# -*- encoding: utf-8 -*-
"""
Имена элементов и атрибутов
"""
import xml.dom.minidom
fh = open("example.xml","r")
doc = xml.dom.minidom.parse(fh)
for node in dom.getElementsByTagName('device'):
print node.getAttribute("name")
for subnode in node.getElementsByTagName('port'):
print subnode.getAttribute("id")
<network>
<device name="Server1">
<description>
<type>host</type>
<vendor>generic</vendor>
<OSType>FreeBSD</OSType>
<OSVersion>7.2</OSVersion>
<OSImage>ftp://frodo.avalon.ru/pub/ISO/FreeBSD</OSImage>
</description>
<interfaces>
<port type="fast ethernet" id="eth0"/>
</interfaces>
<configuration>
<url>nfs://frodo.avalon.ru/pub/FreeBSD-default.xml</url>
</configuration>
</device>
<device name="Router1">
<description>
<type>router</type>
<vendor>cisco</vendor>
<model>2800</model>
<OSType>IOS</OSType>
<OSVersion>12.4</OSVersion>
<OSImage>ftp://frodo.avalon.ru/pub/Cisco/c2800nm</OSImage>
</description>
<interfaces>
<port type="fast ethernet" id="fa0/0"/>
</interfaces>
<configuration>
<url>nfs://frodo.avalon.ru/pub/Cisco2800-default.xml</url>
</configuration>
</device>
</network>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment