Python lxml.etree 模块,Element() 实例源码
我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用lxml.etree.Element()。
def save_opencv_xml_file(path, xml_generator):
"""
Save something in opencv's XML format
@param path: path where to save the file
@param xml_generator: function that accepts an LXML root element as a parameter and generates all the necessary XML
to go in the file
"""
root = etree.Element("opencv_storage")
xml_generator(root)
et = etree.ElementTree(root)
with open(path, 'wb') as f:
et.write(f, encoding="utf-8", xml_declaration=True, pretty_print=True)
# little hack necessary to replace the single quotes (that OpenCV doesn't like) with double quotes
s = open(path).read()
s = s.replace("'", "\"")
with open(path, 'w') as f:
f.write(s)
f.flush()
def update(self, docs, commitwithin=None):
"""Post list of docs to Solr,return URL and status.
Opptionall tell Solr to "commitwithin" that many milliseconds."""
url = self.url + '/update'
add_xml = etree.Element('add')
if commitwithin is not None:
add_xml.set('commitWithin', str(commitwithin))
for doc in docs:
xdoc = etree.SubElement(add_xml, 'doc')
for key, value in doc.iteritems():
if value:
field = etree.Element('field', name=key)
field.text = (value if isinstance(value, unicode)
else str(value))
xdoc.append(field)
request = urllib2.Request(url)
request.add_header('Content-Type', 'text/xml; charset=utf-8')
request.add_data(etree.tostring(add_xml, pretty_print=True))
response = urllib2.urlopen(request).read()
status = etree.XML(response).findtext('lst/int')
return url, status
def create(self, stage=False):
"""Stage or execute a config for creating a VSI
Args:
stage (bool): whether to stage the command or execute immediately
Returns:
True if stage=True and successfully staged
List of etree.Element XML responses if immediately executed
"""
vsi_config = self._build_vsi('merge')
vxlan_config = self._build_vxlan('merge')
if stage:
vsi = self.device.stage_config(vsi_config, 'edit_config')
vxlan = self.device.stage_config(vxlan_config, 'edit_config')
else:
vsi = self.device.edit_config(vsi_config)
vxlan = self.device.edit_config(vxlan_config)
if stage:
return vsi and vxlan
else:
return [vsi, vxlan]
def remove_vsi(self, stage=False, vsi=None):
"""Stage or execute a config for removing a VSI
Args:
stage (bool): whether to stage the command or execute immediately
Returns:
True if stage=True and successfully staged
etree.Element XML response if immediately executed
"""
vsi_config = self._build_vsi('delete', vsi)
if stage:
vsi = self.device.stage_config(vsi_config, 'edit_config')
else:
vsi = self.device.edit_config(vsi_config)
return vsi
def remove_vxlan(self, stage=False):
"""Stage or execute a config for removing a VXLAN
Args:
stage (bool): whether to stage the command or execute immediately
Returns:
True if stage=True and successfully staged
etree.Element XML response if immediately executed
"""
vlan_config = self._build_vxlan('delete')
if stage:
vlan = self.device.stage_config(vlan_config, 'edit_config')
else:
vlan = self.device.edit_config(vlan_config)
return vlan
def save_projects(self, *args):
root = ET.Element("projects")
for project in self.projects_list:
p = ET.SubElement(root, "project")
ET.SubElement(p, "name").text = project.name
ET.SubElement(p, "description").text = project.description
ET.SubElement(p, "path").text = project.path
ET.SubElement(p, "update").text = project.update_cmd
ET.SubElement(p, "compile").text = project.compile_cmd
ET.SubElement(p, "run").text = project.run_cmd
if project.last_update is None:
ET.SubElement(p, "last_update").text = None
else:
ET.SubElement(p, "last_update").text = project.last_update.strftime(settings.DATE_FORMAT)
if project.last_compile is None:
ET.SubElement(p, "last_compile").text = None
else:
ET.SubElement(p, "last_compile").text = project.last_compile.strftime(settings.DATE_FORMAT)
tree = ET.ElementTree(root)
tree.write(settings.PATH_PROJECT_FILE, pretty_print=True)
logging.debug("All projects are saved")
def to_xml(self):
"""Produces an XML out of the point data. disregards the "action" field."""
el = etree.Element(self.osm_type, id=str(self.osm_id), version=str(self.version))
for tag, value in self.tags.items():
etree.SubElement(el, 'tag', k=tag, v=value)
if self.osm_type == 'node':
el.set('lat', str(self.lat))
el.set('lon', str(self.lon))
elif self.osm_type == 'way':
for node_id in self.members:
etree.SubElement(el, 'nd', ref=str(node_id))
elif self.osm_type == 'relation':
for member in self.members:
m = etree.SubElement(el, 'member')
for i, n in enumerate(('type', 'ref', 'role')):
m.set(n, str(member[i]))
return el
def getXML(self) :
# return lxml etree element
graphXML = etree.Element("graph",defaultedgetype=self.type,mode=self.mode,label=self.label,timeformat=self.time_format)
for attributesElement in self.attributes.getAttributesDeclarationXML() :
graphXML.append(attributesElement)
nodesXML = etree.SubElement(graphXML, "nodes")
node_ids=self._nodes.keys()
node_ids.sort()
for id in node_ids :
nodesXML.append(self._nodes[id].getXML())
edgesXML = etree.SubElement(graphXML, "edges")
edge_ids=self._edges.keys()
edge_ids.sort()
for id in edge_ids :
edgesXML.append(self._edges[id].getXML())
return graphXML
def getAttributesDeclarationXML(self) :
""" generate attributes declaration XML """
# return lxml etree element
allAttributesXML=[]
if len(self)>0 :
# iter on node and then edge atts
for attClass,atts in self.iteritems() :
# group by mode
key_mode=lambda att : att["mode"]
atts_sorted_by_mode=sorted(atts.values(),key=key_mode,reverse=True)
for mode,atts in itertools.groupby(atts_sorted_by_mode,key_mode) :
# generate on attributes by mode
attributesXML = etree.Element("attributes")
attributesXML.set("class",attClass)
attributesXML.set("mode",mode)
# generate attribute by id order
for att in sorted(atts,key=lambda att: att["id"]) :
attributeXML=etree.SubElement(attributesXML, "attribute")
attributeXML.set("id",str(att["id"]))
attributeXML.set("title",att["title"])
attributeXML.set("type",att["type"])
if att["defaultValue"] :
etree.SubElement(attributeXML, "default").text=att["defaultValue"]
allAttributesXML.append(attributesXML)
return allAttributesXML
def write(playlists: List[Playlist], target_path: Path, target_library_root: str, source_library_root: str, exclude_playlist_folders: bool = True) -> None:
persistent_id_to_playlist_dict = create_persistent_id_to_playlist_dict(playlists)
filtered_playlist = filter_playlists_if_necessary(playlists, exclude_playlist_folders)
root = etree.Element("rhythmdb-playlists")
for playlist in filtered_playlist:
name = create_playlist_name(playlist, persistent_id_to_playlist_dict)
attributes = {'name': name, 'show-browser': 'true', 'browser-position': "231",
'search-type': "search-match", 'type': "static"}
playlist_element = etree.SubElement(root, "playlist", attributes)
for song in playlist.tracks:
if song.location_escaped is not None:
transformed_location = transform_to_rhythmBox_path(song.location_escaped, target_library_root, source_library_root)
location_element = etree.SubElement(playlist_element, "location")
location_element.text = transformed_location
else:
print(" Can't convert the track [{} - {}] in playlist '{}' because there is no file location defined. It's probably a remote file."
.format(song.artist, song.name, playlist.name))
common.write_to_file(root, target_path, add_standalone_to_xml_declaration=False)
def readxml(self, simType):
path = os.path.dirname(__file__)
if simType == types.TYPE_USIM:
path = os.path.join(path, "sim_files_3g.xml")
else:
path = os.path.join(path, "sim_files_2g.xml")
tree = etree.ElementTree()
if not os.path.exists(path):
logging.warning("File %s not exists" %path)
logging.info("Create xml")
if simType == types.TYPE_USIM:
root = etree.Element('sim_3G')
else:
root = etree.Element('sim_2G')
else:
parser = etree.XMLParser(remove_blank_text=True)
root = etree.parse(path, parser).getroot()
return path, root
def getXML(self) :
# return lxml etree element
graphXML = etree.Element("graph", "edges")
edge_ids=self._edges.keys()
edge_ids.sort()
for id in edge_ids :
edgesXML.append(self._edges[id].getXML())
return graphXML
def pull(self, resource_uri, context, max_elems=100):
"""Executes pull operation over WSMan.
:param resource_uri: URI of resource to pull
:param context: enumeration context
:param max_elems: maximum number of elements returned by the operation
:returns: an lxml.etree.Element object of the response received
:raises: WSManRequestFailure on request failures
:raises: WSManInvalidResponse when receiving invalid response
"""
payload = _PullPayload(self.endpoint,
max_elems)
resp = self._do_request(payload)
resp_xml = ElementTree.fromstring(resp.content)
return resp_xml
def invoke(self, method, selectors, properties):
"""Executes invoke operation over WSMan.
:param resource_uri: URI of resource to invoke
:param method: name of the method to invoke
:param selector: dict of selectors
:param properties: dict of properties
:returns: an lxml.etree.Element object of the response received.
:raises: WSManRequestFailure on request failures
:raises: WSManInvalidResponse when receiving invalid response
"""
payload = _InvokePayload(self.endpoint,
selectors, properties)
resp = self._do_request(payload)
resp_xml = ElementTree.fromstring(resp.content)
return resp_xml
def bug_200709_default_namespace():
"""
>>> e = ET.Element("{default}elem")
>>> s = ET.SubElement(e,"{default}elem")
>>> serialize(e,default_namespace="default") # 1
'<elem xmlns="default"><elem /></elem>'
>>> e = ET.Element("{default}elem")
>>> s = ET.SubElement(e,"{default}elem")
>>> s = ET.SubElement(e,"{not-default}elem")
>>> serialize(e,default_namespace="default") # 2
'<elem xmlns="default" xmlns:ns1="not-default"><elem /><ns1:elem /></elem>'
>>> e = ET.Element("{default}elem")
>>> s = ET.SubElement(e,"elem") # unprefixed name
>>> serialize(e,default_namespace="default") # 3
Traceback (most recent call last):
ValueError: cannot use non-qualified names with default_namespace option
"""
# doesn't work with lxml.etree
def qname():
"""
Test QName handling.
1) decorated tags
>>> elem = ElementTree.Element("{uri}tag")
>>> serialize(elem) # 1.1
'<ns0:tag xmlns:ns0="uri"/>'
## 2) decorated attributes
## >>> elem.attrib["{uri}key"] = "value"
## >>> serialize(elem) # 2.1
## '<ns0:tag ns0:key="value" xmlns:ns0="uri"/>'
"""
def _volume(self, value, cmd='PUT'):
root = etree.Element('YAMAHA_AV')
root.set('cmd', cmd)
system = etree.SubElement(root, 'Main_Zone')
volume = etree.SubElement(system, 'Volume')
level = etree.SubElement(volume, 'Lvl')
if cmd == 'GET':
level.text = value
else:
val = etree.SubElement(level, 'Val')
val.text = str(value)
exponent = etree.SubElement(level, 'Exp')
exponent.text = '1'
unit = etree.SubElement(level, 'Unit')
unit.text = 'dB'
tree = etree.ElementTree(root)
return self._return_document(tree)
def write_xml(input):
"""Writes Sublime Text snippets (Plist)"""
from lxml import etree
completions = input["completions"][0]
data = etree.Element("snippet")
content = etree.SubElement(data, "content")
content.text = etree.CDATA(input["completions"][0]["contents"])
tabTrigger = etree.SubElement(data, "tabTrigger")
tabTrigger.text = input["completions"][0]['trigger']
scope = etree.SubElement(data, "scope")
scope.text = input["scope"]
if 'description' in input['completions'][0]:
description = etree.SubElement(data, "description")
description.text = input["completions"][0]["description"]
output = etree.tostring(data, pretty_print=True, encoding="utf-8").decode('utf-8')
return output
def rpc_create_subscription(self, unused_session, rpc, *unused_params):
logger.info("rpc_create-subscription")
logger.debug("Session:%s", format(unused_session))
logger.debug("RPC received:%s", format(etree.tostring(rpc)))
for param in unused_params:
logger.debug("Param:" + etree.tostring(param))
unused_session.subscription_active = True
return etree.Element("ok")
# **********************************
# Setup SNMP
# **********************************
def fixml_buy_Now(self, ticker, quantity, limit):
"""Generates the FIXML for a buy order."""
fixml = Element("FIXML")
fixml.set("xmlns", FIXML_NAMESPACE)
order = SubElement(fixml, "Order")
order.set("TmInForce", "0") # Day order
order.set("Typ", "2") # Limit
order.set("Side", "1") # Buy
order.set("Px", "%.2f" % limit) # Limit price
order.set("Acct", TradEKING_ACCOUNT_NUMBER)
instrmt = SubElement(order, "Instrmt")
instrmt.set("SecTyp", "CS") # Common stock
instrmt.set("Sym", ticker)
ord_qty = SubElement(order, "OrdQty")
ord_qty.set("Qty", str(quantity))
return tostring(fixml)
def fixml_sell_eod(self, limit):
"""Generates the FIXML for a sell order."""
fixml = Element("FIXML")
fixml.set("xmlns", "7") # Market on close
order.set("Typ", "2") # Sell
order.set("Px", str(quantity))
return tostring(fixml)
def fixml_short_Now(self, limit):
"""Generates the FIXML for a sell short order."""
fixml = Element("FIXML")
fixml.set("xmlns", "5") # Sell short
order.set("Px", str(quantity))
return tostring(fixml)
def fixml_cover_eod(self, limit):
"""Generates the FIXML for a sell to cover order."""
fixml = Element("FIXML")
fixml.set("xmlns", "%.2f" % limit) # Limit price
order.set("AcctTyp", "5") # Cover
order.set("Acct", str(quantity))
return tostring(fixml)
def genAdvertNode(self, _urn_authority, _my_urn):
"""
Returns a etree.Element containing advertisement info for this resource
:param _my_urn: URN of the resource
:type _my_urn: str
:param _urn_authority: URN of the authority/AM
:type _urn_authority: str
:rtype: Element
"""
# Actual resources should add some information like sliver_type
r = etree.Element("node")
resource_id = str(self.id)
resource_available = str(self.available).lower()
resource_urn = self.urn(_urn_authority)
r.set("component_manager_id", _my_urn)
r.set("component_name", resource_id)
r.set("component_id", resource_urn)
r.set("exclusive", "false")
etree.SubElement(r, "available").set("Now", resource_available)
for sliver_type_name in self.supported_sliver_types:
etree.SubElement(r, "sliver_type").set("name", sliver_type_name)
return r
def manifestAuth(self):
super(ResourceExample, self).deprovision()
if len(self.getUsers())==0:
return []
else:
ret = []
for login in self.getUsers():
auth=etree.Element("login")
auth.set("authentication","ssh-keys")
auth.set("hostname", self.host)
auth.set("port", str(self.getPort()))
auth.set("username", login)
ret.append(auth)
return ret
#A blocking (while ...) method. Return True when the resource is up and ready,or False if you set a timeout
def manifestAuth(self):
super(DockerContainer, self).manifestAuth()
if len(self.getUsers())==0:
return []
else:
ret = []
for login in self.getUsers():
auth=etree.Element("login")
auth.set("authentication", login)
ret.append(auth)
if self.ipv6 is not None:
auth=etree.Element("login")
auth.set("authentication","ssh-keys")
auth.set("hostname", str(self.ipv6))
auth.set("port", "22")
auth.set("username", login)
ret.append(auth)
return ret
def depccg2xml(tree, sid):
def traverse(node, spid=0):
id = "s{}_sp{}".format(sid, spid)
xml_node = etree.SubElement(res, "span")
xml_node.set("category", str(node.cat))
xml_node.set("begin", str(node.start_of_span))
xml_node.set("end", str(node.start_of_span+len(node)))
xml_node.set("id", id)
if node.is_leaf:
xml_node.set("terminal",
"s{}_{}".format(sid, node.head_id))
else:
spid, childid = traverse(node.left_child, spid+1)
if not node.is_unary:
spid, tmp = traverse(node.right_child, spid+1)
childid += " " + tmp
xml_node.set("child", childid)
xml_node.set("rule", node.op_string)
return spid, id
res = etree.Element("ccg")
res.set("id", "s{}_ccg0".format(sid))
_, id = traverse(tree)
res.set("root", str(id))
return res
def __init__(self, name=None, element=None, icon=None):
if element is None:
element = Element('Group')
name = xmlfactory.create_name_element(name)
uuid = xmlfactory.create_uuid_element()
element.append(uuid)
element.append(name)
if icon:
icon_el = xmlfactory.create_icon_element(icon)
element.append(icon_el)
assert type(element) in [_Element, Element, ObjectifiedElement], \
'The provided element is not an LXML Element,but {}'.format(
type(element)
)
assert element.tag == 'Group', 'The provided element is not a Group '\
'element,but a {}'.format(element.tag)
self._element = element
def create_figcaption(img, figure):
figcaption = etree.Element('figcaption')
create = False
if img.tail:
create = True
figcaption.text = img.tail
img.tail = ''
for sibling in img.itersiblings():
create = True
figcaption.append(sibling)
if not create:
return
figcaption.set('class', 'figure-caption')
figure.append(figcaption)
def create_img_thumbnail(img, content_dir):
img_src = img.get('src')
if img_src.startswith('http'):
logger.warning('Found remotely linked image: %s', img_src)
else:
filename = get_image_filename(content_dir, img_src)
info = get_image_info(filename)
if info['is_image']:
if info['needs_click_to_enlarge']:
wrap_element(img, etree.Element('a', attrib={
'href': img_src,
'target': '_blank',
'title': img.get('alt'),
}))
if info['needs_thumbnail']:
tn_filename = create_thumbnail(filename)
img.set('src', get_image_src(tn_filename))
else:
logger.error('Found non-existing image: %s', img_src)
def make_element(tag, namespace_s=None):
""" This handler creates an empty element with the given ``tag``. The tag can have a prefix.
If ``namespace_s`` is ``None`` the namespace mapping of the :term:`transformation root`
is used as context. If given as :term:`mapping`,this is used as context.
It can also be provided as string,which is then used as default namespace. """
def handler(transformation, nsmap):
if is_Ref(tag):
_tag = tag(transformation)
else:
_tag = tag
if namespace_s is None:
_namespace_s = nsmap
elif is_Ref(namespace_s):
_namespace_s = namespace_s(transformation)
else:
_namespace_s = namespace_s
if isinstance(_namespace_s, str):
return etree.Element('{' + _namespace_s + '}' + _tag)
else:
if ':' in _tag:
prefix, _tag = _tag.split(':', 1)
_tag = '{' + _namespace_s[prefix] + '}' + _tag
return etree.Element(_tag, nsmap=_namespace_s)
return handler
def test_grouped_steps():
def append_to_list(value):
def appender(list):
list.append(value)
return appender
stpgrp_c = (append_to_list(3), append_to_list(4))
stpgrp_b = (append_to_list(2), stpgrp_c, append_to_list(5))
stpgrp_a = (append_to_list(1))
transformation = Transformation(
append_to_list(0),
stpgrp_a,
stpgrp_b,
context={'list': []}, result_object='context.list'
)
result = transformation(etree.Element('root'))
for exp, val in enumerate(result):
assert exp == val
def test_wikipedia_example_1():
expected = parse("""
<root>
<name username="JS1">John</name>
<name username="MI1">Morka</name>
</root>
""")
def extract_person(element):
return element.attrib['username'], element.find('name').text
def append_person(prevIoUs_result, result):
lxml_utils.subelement(result, 'name', {'username': prevIoUs_result[0]},
text=prevIoUs_result[1])
transformation = Transformation(
Rule('person', (extract_person, append_person)),
result_object='context.result', context={'result': etree.Element('root')})
# that's five (or not counting line-breaks: nine) lines less sloc than the XSLT implementation
assert equal_subtree(transformation(wp_document), expected)
def __generate_reference__(self, triple_map, **kwargs):
"""Internal method takes a triple_map and returns the result of
applying to XPath to the current DOM context
Args:
-----
triple_map: SimpleNamespace
element: etree.Element
"""
element = kwargs.get("element")
found_elements = element.xpath(
triple_map.reference,
namespaces=self.xml_ns)
for elem in found_elements:
raw_text = elem.text.strip()
#! Quick and dirty test for valid URI
if not raw_text.startswith("http"):
continue
return rdflib.URIRef(raw_text)
def xml_set_attribv_occ(xmltree, xpathn, attributename, attribv, occ=[0], create=False):
"""
Routine sets the value of an attribute in the xml file on only the places
specified in occ
:param: an etree a xpath from root to the attribute and the attribute value
:param: occ,list of integers
:return: None,or an etree
Comment: Element.set will add the attribute if it does not exist,
xpath expression has to exist
example: xml_set_first_attribv(tree,'/fleurInput/calculationSetup','band','T')
xml_set_first_attribv(tree,'dos','F')
"""
root = xmltree.getroot()
nodes = eval_xpath3(root, create=create)
#print 'nodes from xml_set_attribv_occ: {}'.format(nodes)
if type(attribv) != type(''):
attribv = str(attribv)
for i, node in enumerate(nodes):
if i in occ:
node.set(attributename, attribv)
if -1 in occ:# 'all'
node.set(attributename, attribv)
def xml_set_first_attribv(xmltree, create=False):
"""
Routine sets the value of an attribute in the xml file
:param: an etree a xpath from root to the attribute and the attribute value
:return: None,'F')
"""
root = xmltree.getroot()
if type(attribv) == type(''):
eval_xpath3(root, create=create)[0].set(attributename, attribv)
else:
eval_xpath3(root, str(attribv))
#return xmltree
#Todo check if worked. else exception,
def sortFile(fileobj):
with open(fileobj['filename'], 'r') as original:
# parse the XML file and get a pointer to the top
xmldoc = le.parse(original)
xmlroot = xmldoc.getroot()
# create a new XML element that will be the top of
# the sorted copy of the XML file
newxmlroot = le.Element(xmlroot.tag)
# create the sorted copy of the XML file
sortAttrs(xmlroot, newxmlroot)
sortElements(list(xmlroot), newxmlroot)
# write the sorted XML file to the temp file
newtree = le.ElementTree(newxmlroot)
with open(fileobj['tmpfilename'], 'wb') as newfile:
newtree.write(newfile, pretty_print=True)
#
# sort each of the specified files
def trans_root(description,copyright,Annotation):
"""Some basic information about the document """
username = str(getpass.getuser())
py_version = "0.1"
PMML_version = "4.3"
xmlns = "http://www.dmg.org/PMML-4_2"
PMML = root = Element('pmml',xmlns=xmlns, version=PMML_version)
# pmml level
if copyright is None:
copyright = "copyright (c) 2015 {0}".format(username)
if description is None:
description = "Gaussian Process Model"
Header = SubElement(PMML,"header",copyright=copyright,description=description)
if Annotation is not None:
ET.Element(Header,"Annotation").text=Annotation
return PMML
def write_linestring(pyptlist):
"""
This function writes a GML linestring member.
Parameters
----------
pyptlist : a list of tuples
List of points to be converted. A pypt is a tuple that documents the xyz coordinates of a pt e.g. (x,y,z),
thus a pyptlist is a list of tuples e.g. [(x1,y1,z1),(x2,y2,z2),...]
Returns
-------
linestring member : lxml Element
The lxml linestring member.
"""
gml_Linestring = Element("{" + XMLNamespaces.gml+ "}" + 'Linestring')
gml_posList = SubElement(gml_Linestring, "{" + XMLNamespaces.gml+ "}" + 'posList')
gml_posList.attrib['srsDimension'] = '3'
gml_posList.text = pos_list2text(pyptlist)
return gml_Linestring
def write_pt(pypt):
"""
This function writes a GML point member.
Parameters
----------
pypt : tuple of floats
A pypt is a tuple that documents the xyz coordinates of a pt e.g. (x,z).
Returns
-------
point member : lxml Element
The lxml point member.
"""
gml_Point = Element("{" + XMLNamespaces.gml+ "}" + 'Point')
gml_pos = SubElement(gml_Point,"{" + XMLNamespaces.gml+ "}" + 'pos')
gml_pos.attrib['srsDimension'] = "3"
gml_pos.text = str(pypt[0]) + " " + str(pypt[1]) + " " + str(pypt[2])
return gml_pos
def get_landuses(self):
"""
This function gets the landuse cityobject.
Returns
-------
landuses : list of lxml Elements
List of landuses lxml Element.
"""
landuses = []
cityobjectmembers = self.cityobjectmembers
for cityobject in cityobjectmembers:
landuse = cityobject.find("luse:LandUse", namespaces=self.namespaces)
if landuse is not None:
landuses.append(landuse)
return landuses
def get_roads(self):
"""
This function gets the roads cityobject.
Returns
-------
roads : list of lxml Elements
List of roads lxml Element.
"""
roads = []
cityobjectmembers = self.cityobjectmembers
for cityobject in cityobjectmembers:
road = cityobject.find("trans:Road", namespaces=self.namespaces)
if road is not None:
roads.append(road)
return roads
def get_building_height(self, lxmlbuilding):
"""
This function gets the height of the building.
Parameters
----------
lxmlbuilding : lxml Element
A lxml building object.
Returns
-------
building height : float
The building height,if attribute is not available return None.
"""
height = lxmlbuilding.find("bldg:measuredHeight", namespaces=self.namespaces)
if height != None:
return float(height.text)
else:
return None
def get_building_storey(self, lxmlbuilding):
"""
This function gets the number of building storey above ground of the building.
Parameters
----------
lxmlbuilding : lxml Element
A lxml building object.
Returns
-------
building storey above ground : int
The building storey above ground,if attribute is not available return None.
"""
storey = lxmlbuilding.find("bldg:storeysAboveGround", namespaces=self.namespaces)
if storey != None:
return int(storey.text)
else:
return None
def get_building_function(self,lxmlbuilding):
"""
This function gets the function of the building.
Parameters
----------
lxmlbuilding : lxml Element
A lxml building object.
Returns
-------
building function code : str
The building function in gml code,if attribute is not available return None.
"""
function = lxmlbuilding.find("bldg:function", namespaces=self.namespaces)
if function != None:
return function.text
else:
return None
def get_building_class(self,lxmlbuilding):
"""
This function gets the class of the building.
Parameters
----------
lxmlbuilding : lxml Element
A lxml building object.
Returns
-------
building class code : str
The building class in gml code,if attribute is not available return None.
"""
bclass = lxmlbuilding.find("bldg:class", namespaces=self.namespaces)
if bclass != None:
return bclass.text
else:
return None
def get_building_yr_constr(self, lxmlbuilding):
"""
This function gets year of construction of the building.
Parameters
----------
lxmlbuilding : lxml Element
A lxml building object.
Returns
-------
building year of construction : str
The building year of construction,if attribute is not available return None.
"""
constr = lxmlbuilding.find("bldg:yearOfConstruction", namespaces=self.namespaces)
if constr != None:
return constr.text
else:
return None
def get_building_rooftype(self, lxmlbuilding):
"""
This function gets year of construction of the building.
Parameters
----------
lxmlbuilding : lxml Element
A lxml building object.
Returns
-------
building rooftype : str
The building rooftype in gml code,if attribute is not available return None.
"""
rooftype = lxmlbuilding.find("bldg:roofType", namespaces=self.namespaces)
if rooftype != None:
return rooftype.text
else:
return None
def convert(parent, entry):
if isinstance(parent, str):
parent = etree.Element(parent)
if isinstance(entry, dict):
return _convert_dict(parent, entry)
elif isinstance(entry, list):
return _convert_list(parent, entry)
elif etree.iselement(entry):
parent.append(entry)
else:
parent.text = str(entry)