Page Menu
Home
c4science
Search
Configure Global Search
Log In
Files
F61172334
attachable_object.py
No One
Temporary
Actions
Download File
Edit File
Delete File
View Transforms
Subscribe
Mute Notifications
Award Token
Subscribers
None
File Metadata
Details
File Info
Storage
Attached
Created
Sun, May 5, 00:05
Size
2 KB
Mime Type
text/x-python
Expires
Tue, May 7, 00:05 (1 d, 23 h)
Engine
blob
Format
Raw Data
Handle
17447991
Attached To
rNIETZSCHEPYTHON nietzsche-python
attachable_object.py
View Options
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
""" This is an abstract class for all objects that can be attached to a lxml.etree.
"""
# Copyright (C) University of Basel 2019 {{{1
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/> 1}}}
__author__
=
"Christian Steiner"
__maintainer__
=
__author__
__copyright__
=
'University of Basel'
__email__
=
"christian.steiner@unibas.ch"
__status__
=
"Development"
__license__
=
"GPL v3"
__version__
=
"0.0.1"
import
abc
import
lxml.etree
as
ET
class
AttachableObject
(
metaclass
=
abc
.
ABCMeta
):
"""
This is an abstract class for all objects that can be attached to a lxml.etree..
"""
XML_TAG
=
'attachable'
@abc.abstractmethod
def
attach_object_to_tree
(
self
,
target_tree
):
"""Attach object to tree.
"""
pass
def
get_or_create_node
(
self
,
target_tree
):
"""Return xml node of attable object.
"""
if
target_tree
.
__class__
.
__name__
==
'_ElementTree'
:
target_tree
=
target_tree
.
getroot
()
obj_node
=
target_tree
.
xpath
(
'.//'
+
self
.
XML_TAG
)[
0
]
\
if
(
len
(
target_tree
.
xpath
(
'.//'
+
self
.
XML_TAG
))
>
0
)
\
else
ET
.
SubElement
(
target_tree
,
self
.
XML_TAG
)
return
obj_node
def
get_or_create_node_with_id
(
self
,
target_tree
):
"""Return xml node of attable object.
"""
if
'id'
not
in
self
.
__dict__
:
return
self
.
get_or_create_node
(
target_tree
)
if
target_tree
.
__class__
.
__name__
==
'_ElementTree'
:
target_tree
=
target_tree
.
getroot
()
if
len
(
target_tree
.
xpath
(
'.//'
+
self
.
XML_TAG
+
'[@id="
%s
"]'
%
self
.
id
))
>
0
:
obj_node
=
target_tree
.
xpath
(
'.//'
+
self
.
XML_TAG
+
'[@id="
%s
"]'
%
self
.
id
)[
0
]
obj_node
.
getparent
()
.
remove
(
obj_node
)
return
ET
.
SubElement
(
target_tree
,
self
.
XML_TAG
,
attrib
=
{
'id'
:
str
(
self
.
id
)})
Event Timeline
Log In to Comment