本文整理汇总了Python中xml.etree.ElementTree.XMLParser方法的典型用法代码示例。如果您正苦于以下问题:Python ElementTree.XMLParser方法的具体用法?Python ElementTree.XMLParser怎么用?Python ElementTree.XMLParser使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类xml.etree.ElementTree
的用法示例。
在下文中一共展示了ElementTree.XMLParser方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: parse
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import XMLParser [as 别名]
def parse(source, binaryfp=None):
"""Parse ArtsXML file from source.
Args:
source (str): Filename or file pointer.
Returns:
xml.etree.ElementTree: XML Tree of the ARTS data file.
"""
arts_element = type('ARTSElementBinaryFP',
ARTSElement.__bases__,
dict(ARTSElement.__dict__))
arts_element.binaryfp = binaryfp
return ElementTree.parse(source,
parser=ElementTree.XMLParser(
target=ElementTree.TreeBuilder(
element_factory=arts_element)))
示例2: bug_200708_close
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import XMLParser [as 别名]
def bug_200708_close():
"""
Test default builder.
>>> parser = ET.XMLParser() # default
>>> parser.feed("<element>some text</element>")
>>> summarize(parser.close())
'element'
Test custom builder.
>>> class EchoTarget:
... def close(self):
... return ET.Element("element") # simulate root
>>> parser = ET.XMLParser(EchoTarget())
>>> parser.feed("<element>some text</element>")
>>> summarize(parser.close())
'element'
"""
示例3: __init__
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import XMLParser [as 别名]
def __init__(self, xml=None, rootnode=None):
if xml is None and rootnode is None:
xml = default_xml
if rootnode is None:
if sys.platform.startswith('win'):
enc = 'ISO-8859-1'
else:
enc = 'UTF-8'
self.dom = ElementTree.fromstring(xml, ElementTree.XMLParser(encoding=enc))
else:
self.dom = rootnode
# determine OME namespaces
self.ns = get_namespaces(self.dom)
if __name__ == '__main__':
if self.ns['ome'] is None:
raise Exception("Error: String not in OME-XML format")
# generate a uuid if there is none
# < OME UUID = "urn:uuid:ef8af211-b6c1-44d4-97de-daca46f16346"
omeElem = self.dom
if not omeElem.get('UUID'):
omeElem.set('UUID', 'urn:uuid:'+str(uuid.uuid4()))
self.uuidStr = omeElem.get('UUID')
示例4: fetch_filtered_daily_feeds
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import XMLParser [as 别名]
def fetch_filtered_daily_feeds(self, day, filter_parm):
""" Fetch the feed for +day+ and returns an ElementTree instance. """
# import xml.etree.ElementTree as ET
from xml.etree import ElementTree
from htmlentitydefs import name2codepoint
if self.FEED_PASSWORD is None:
raise ValueError("%s.FEED_PASSWORD must be set." % self.__class__.__name__)
r = requests.get(self.FEED_FILTER_URL % (day.strftime('%d-%m-%Y'), filter_parm),
auth=(self.FEED_USER, self.FEED_PASSWORD),
verify=False,
timeout=60)
r.raise_for_status()
parser = ElementTree.XMLParser()
parser.parser.UseForeignDTD(True)
parser.entity.update((x, unichr(i)) for x, i in name2codepoint.iteritems())
etree = ElementTree
return etree.fromstring(r.text.encode('utf-8'), parser=parser)
示例5: fetch_daily_feeds
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import XMLParser [as 别名]
def fetch_daily_feeds(self, day):
""" Fetch the feed for +day+ and returns an ElementTree instance. """
# import xml.etree.ElementTree as ET
from xml.etree import ElementTree
from htmlentitydefs import name2codepoint
if self.FEED_PASSWORD is None:
raise ValueError("%s.FEED_PASSWORD must be set." % self.__class__.__name__)
r = requests.get(self.FEED_URL % day.strftime('%d-%m-%Y'),
auth=(self.FEED_USER, self.FEED_PASSWORD),
verify=False,
timeout=60)
r.raise_for_status()
parser = ElementTree.XMLParser()
parser.parser.UseForeignDTD(True)
parser.entity.update((x, unichr(i)) for x, i in name2codepoint.iteritems())
etree = ElementTree
return etree.fromstring(r.text.encode('utf-8'), parser=parser)
示例6: read
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import XMLParser [as 别名]
def read(self):
parser = ET.XMLParser()
tree = ET.parse(self.filename, parser)
root = tree.getroot()
if root.tag != "Xdmf":
raise ReadError()
version = root.get("Version")
if version.split(".")[0] == "2":
return self.read_xdmf2(root)
if version.split(".")[0] != "3":
raise ReadError("Unknown XDMF version {}.".format(version))
return self.read_xdmf3(root)
示例7: parse_impl
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import XMLParser [as 别名]
def parse_impl(self):
"""
Parses the HTML content as a stream. This is far less memory
intensive than loading the entire HTML file into memory, like
BeautifulSoup does.
"""
# Cast to str to ensure not unicode under Python 2, as the parser
# doesn't like that.
parser = XMLParser(encoding=str('UTF-8'))
element_iter = ET.iterparse(self.handle, events=("start", "end"), parser=parser)
for pos, element in element_iter:
tag, class_attr = _tag_and_class_attr(element)
if tag == "h1" and pos == "end":
if not self.user:
self.user = element.text.strip()
elif tag == "div" and "thread" in class_attr and pos == "start":
participants = self.parse_participants(element)
thread = self.parse_thread(participants, element_iter, True)
self.save_thread(thread)
示例8: entity
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import XMLParser [as 别名]
def entity():
"""
Test entity handling.
1) good entities
>>> e = ET.XML("<document title='舰'>test</document>")
>>> serialize(e)
'<document title="舰">test</document>'
2) bad entities
>>> ET.XML("<document>&entity;</document>")
Traceback (most recent call last):
ParseError: undefined entity: line 1, column 10
>>> ET.XML(ENTITY_XML)
Traceback (most recent call last):
ParseError: undefined entity &entity;: line 5, column 10
3) custom entity
>>> parser = ET.XMLParser()
>>> parser.entity["entity"] = "text"
>>> parser.feed(ENTITY_XML)
>>> root = parser.close()
>>> serialize(root)
'<document>text</document>'
"""
示例9: load_xml
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import XMLParser [as 别名]
def load_xml(file_name): # Load an XML file
try:
parser = ET.XMLParser(encoding="utf-8")
return ET.parse(base_dir() + file_name, parser=parser)
except IOError as ex:
if ex.errno == 2:
raise e.FileNotFound
else:
raise e.LoadFileException(str(ex)+'\nUnable to load XML ' + base_dir() + file_name)
示例10: extract_needs_from_html
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import XMLParser [as 别名]
def extract_needs_from_html(html):
# Replace entities, which elementTree can not handle
html = html.replace('©', '')
html = html.replace('&', '')
if sys.version_info >= (3, 0):
source = StringIO(html)
parser = ElementTree.XMLParser(encoding="utf-8")
else: # Python 2.x
source = StringIO(html.encode("utf-8"))
parser = ElementTree.XMLParser(encoding="utf-8")
# XML knows not nbsp definition, which comes from HTML.
# So we need to add it
parser.entity["nbsp"] = ' '
etree = ElementTree.ElementTree()
document = etree.parse(source, parser=parser)
tables = document.findall(".//html:table", NS)
# Sphinx <3.0 start html-code with:
# <html xmlns="http://www.w3.org/1999/xhtml">
# Sphinx >= 3.0 starts it with:
# <html>
# So above search will not work for Sphinx >= 3.0 and we try a new one
if len(tables) == 0:
tables = document.findall(".//html:table", {'html': ''})
return [HtmlNeed(table) for table in tables if 'need' in table.get('class', '')]
示例11: __init__
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import XMLParser [as 别名]
def __init__(self):
self.tree_builder = _TerminationDetectingTreeBuilder()
self.xml_tree_builder = et.XMLParser(target=self.tree_builder)
示例12: read_xml
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import XMLParser [as 别名]
def read_xml():
if not xbmcvfs.exists(FILENAME):
return ET.Element(ROOT_TAG)
parser = ET.XMLParser(target=CommentedTreeBuilder())
with closing(xbmcvfs.File(FILENAME)) as as_xml:
try:
return ET.parse(as_xml, parser).getroot()
except ET.ParseError:
log("Can't parse advancedsettings.xml", xbmc.LOGWARNING)
示例13: parseMeta
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import XMLParser [as 别名]
def parseMeta(self, schid, clid):
(error, meta) = ts3.getClientVariable(schid, clid, ts3defines.ClientProperties.CLIENT_META_DATA)
# print(re.search('(<{0}.*>.*</{0}>)'.format(self.tag), meta))
try: meta = re.search('<{0}>(.*)</{0}>'.format(self.tag), meta).group(0)
except AttributeError: return False
# print('meta_strip: %s'%meta.strip())
# print('xml: %s'%xml.fromstring(meta.strip(), parser = xml.XMLParser(encoding="utf-8")))
# print('xml_sub: %s'%xml.fromstring(meta.strip(), parser = xml.XMLParser(encoding="utf-8")).getchildren())
# print('xml_sub[0]: %s'%xml.fromstring(meta.strip(), parser = xml.XMLParser(encoding="utf-8")).getchildren()[0])
return xml.fromstring(meta.strip(), parser = xml.XMLParser(encoding="utf-8")).getchildren()[0]
示例14: getresponse
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import XMLParser [as 别名]
def getresponse(self,input):
lines=input.split(b"<?xml")
content = {}
for line in lines:
if line==b'':
continue
line=b"<?xml"+line
parser = ET.XMLParser(encoding="utf-8")
tree = ET.fromstring(line, parser=parser)
e = ET.ElementTree(tree).getroot()
for atype in e.findall('response'):
for field in atype.attrib:
content[field]=atype.attrib[field]
return content
示例15: getlog
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import XMLParser [as 别名]
def getlog(self,input):
lines=input.split(b"<?xml")
data = []
for line in lines:
if line==b'':
continue
line=b"<?xml"+line
parser = ET.XMLParser(encoding="utf-8")
tree = ET.fromstring(line, parser=parser)
e = ET.ElementTree(tree).getroot()
for atype in e.findall('log'):
if 'value' in atype.attrib:
data.append(atype.attrib['value'])
return data