本文整理汇总了Python中xml.sax.xmlreader.InputSource类的典型用法代码示例。如果您正苦于以下问题:Python InputSource类的具体用法?Python InputSource怎么用?Python InputSource使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了InputSource类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: parse
def parse(self, xml, source='string'):
'''Parses a XML stream.
* If p_source is "string", p_xml must be a string containing
valid XML content.
* If p_source is "file": p_xml can be:
- a string containing the path to the XML file on disk;
- a file instance opened for reading. Note that in this case, this
method will close it.
'''
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
self.parser.setContentHandler(self)
self.parser.setErrorHandler(self)
self.parser.setFeature(feature_external_ges, False)
inputSource = InputSource()
if source == 'string':
inputSource.setByteStream(StringIO(xml))
else:
if not isinstance(xml, file):
xml = file(xml)
inputSource.setByteStream(xml)
self.parser.parse(inputSource)
if isinstance(xml, file): xml.close()
return self.res
开发者ID:thefrolov,项目名称:open-drug-store,代码行数:26,代码来源:xml_parser.py
示例2: create
def create(self,request, user_name, vendor, name, version):
user = user_authentication(user_name)
# Get the xml containing the tags from the request
tags_xml = request.__getitem__('tags_xml')
# Parse the xml containing the tags
parser = make_parser()
handler = TagsXMLHandler()
# Tell the parser to use our handler
parser.setContentHandler(handler)
# Parse the input
try:
from StringIO import StringIO
except ImportError:
from cStringIO import StringIO
inpsrc = InputSource()
inpsrc.setByteStream(StringIO(tags_xml))
parser.parse(inpsrc)
# Get the gadget's id for those vendor, name and version
gadget = get_object_or_404(GadgetResource, short_name=name,vendor=vendor,version=version)
# Insert the tags for these resource and user in the database
for e in handler._tags:
try:
UserTag.objects.get_or_create(tag=e, idUser=user, idResource=gadget)
except:
return HttpResponseServerError(get_xml_error(str(sys.exc_info()[1])),mimetype='text/xml; charset=UTF-8')
response = '<?xml version="1.0" encoding="UTF-8" ?>\n'
response += get_tags_by_resource(gadget, user)
return HttpResponse(response,mimetype='text/xml; charset=UTF-8')
开发者ID:conwetlab,项目名称:ezwebplatform,代码行数:35,代码来源:views.py
示例3: rootElement
def rootElement(self):
# Get the context that was originally generated during startup and
# create a new context using its registrations
real_context = zope.app.appsetup.appsetup.getConfigContext()
context = config.ConfigurationMachine()
context._registry = copy.copy(real_context._registry)
context._features = copy.copy(real_context._features)
context.package = self.package
# Shut up i18n domain complaints
context.i18n_domain = 'zope'
# Since we want to use a custom configuration handler, we need to
# instantiate the parser object ourselves
parser = make_parser()
handler = MyConfigHandler(context)
parser.setContentHandler(handler)
parser.setFeature(feature_namespaces, True)
# Now open the file
file = open(self.filename)
src = InputSource(getattr(file, 'name', '<string>'))
src.setByteStream(file)
# and parse it
parser.parse(src)
# Finally we retrieve the root element, have it provide a special root
# directive interface and give it a location, so that we can do local
# lookups.
root = handler.rootElement
directlyProvides(root, IRootDirective)
root.__parent__ = self
return root
开发者ID:zopefoundation,项目名称:zope.app.apidoc,代码行数:34,代码来源:zcml.py
示例4: AbstractXMLLoader
class AbstractXMLLoader(AbstractLoader, handler.ContentHandler):
xml_reader = None
input_source = None
def init_load(self):
self.input_source = InputSource()
self.input_source.setByteStream(self.fileptr)
self.xml_reader = xml.sax.make_parser()
self.xml_reader.setContentHandler(self)
self.xml_reader.setErrorHandler(ErrorHandler())
self.xml_reader.setEntityResolver(EntityResolver())
self.xml_reader.setDTDHandler(DTDHandler())
self.do_load()
def start_parsing(self):
self.xml_reader.parse(self.input_source)
def startElement(self, name, attrs):
self.start_element(name, attrs)
def endElement(self, name):
self.end_element(name)
def characters(self, data):
self.element_data(data)
def start_element(self, name, attrs):pass
def end_element(self, name):pass
def element_data(self, data):pass
开发者ID:Scrik,项目名称:sk1-wx,代码行数:30,代码来源:generic_filters.py
示例5: limit_featurecollection
def limit_featurecollection(content, limit=200):
"""
Parse a WFS FeatureCollection XML string and produce a
similar string with at most 200 features.
"""
parser = make_parser()
_input = BytesIO(content)
input_source = InputSource()
input_source.setByteStream(_input)
output = StringIO()
downstream = XMLGenerator(output, 'utf-8')
_filter = _XMLFilterLimit(parser, downstream, limit=limit)
_filter.parse(input_source)
result = output.getvalue()
_input.close()
output.close()
return result
开发者ID:sitn,项目名称:crdppf_core,代码行数:25,代码来源:wfsparsing.py
示例6: countriesSource
def countriesSource() -> InputSource:
'''
Provides the countries input source for the XML.
'''
source = InputSource()
source.setByteStream(openURI(path.join(path.dirname(__file__), 'iso_3166-1_list_en.xml')))
return source
开发者ID:adityaathalye,项目名称:Superdesk,代码行数:7,代码来源:countries.py
示例7: create
def create(self, request, vendor, name, version):
format = request.POST.get('format', 'default')
# Get the xml containing the tags from the request
tags_xml = request.POST.get('tags_xml')
tags_xml = tags_xml.encode("utf-8")
# Parse the xml containing the tags
parser = make_parser()
handler = TagsXMLHandler()
# Tell the parser to use our handler
parser.setContentHandler(handler)
# Parse the input
inpsrc = InputSource()
inpsrc.setByteStream(StringIO(tags_xml))
parser.parse(inpsrc)
# Get the resource's id for those vendor, name and version
resource = get_object_or_404(CatalogueResource, short_name=name,
vendor=vendor, version=version)
# Insert the tags for these resource and user in the database
for e in handler._tags:
tag_resource(request.user, e, resource)
return get_tag_response(resource, request.user, format)
开发者ID:Robinlovelace,项目名称:wirecloud,代码行数:28,代码来源:views.py
示例8: __loadxmlparts
def __loadxmlparts(z, manifest, doc, objectpath):
from load import LoadParser
from xml.sax import make_parser, handler
for xmlfile in (
objectpath +
'settings.xml',
objectpath +
'meta.xml',
objectpath +
'content.xml',
objectpath +
'styles.xml'):
if xmlfile not in manifest:
continue
try:
xmlpart = z.read(xmlfile)
doc._parsing = xmlfile
parser = make_parser()
parser.setFeature(handler.feature_namespaces, 1)
parser.setContentHandler(LoadParser(doc))
parser.setErrorHandler(handler.ErrorHandler())
inpsrc = InputSource()
inpsrc.setByteStream(StringIO(xmlpart))
parser.parse(inpsrc)
del doc._parsing
except KeyError as v:
pass
开发者ID:Daksh,项目名称:portfolio,代码行数:30,代码来源:opendocument.py
示例9: load
def load(odffile):
""" Load an ODF file into memory
Returns a reference to the structure
"""
from load import LoadParser
from xml.sax import make_parser, handler
z = zipfile.ZipFile(odffile)
mimetype = z.read("mimetype")
doc = OpenDocument(mimetype, add_generator=False)
# Look in the manifest file to see if which of the four files there are
manifestpart = z.read("META-INF/manifest.xml")
manifest = manifestlist(manifestpart)
for xmlfile in ("settings.xml", "meta.xml", "content.xml", "styles.xml"):
if not manifest.has_key(xmlfile):
continue
try:
xmlpart = z.read(xmlfile)
doc._parsing = xmlfile
parser = make_parser()
parser.setFeature(handler.feature_namespaces, 1)
parser.setContentHandler(LoadParser(doc))
parser.setErrorHandler(handler.ErrorHandler())
inpsrc = InputSource()
inpsrc.setByteStream(StringIO(xmlpart))
parser.parse(inpsrc)
del doc._parsing
except KeyError, v:
pass
开发者ID:CrypticGator,项目名称:rmtoo,代码行数:32,代码来源:opendocument.py
示例10: Load
def Load(self):
try:
self.document()
self.layer()
error_handler = ErrorHandler()
entity_resolver = EntityResolver()
dtd_handler = DTDHandler()
input = open(self.filename, "r")
input_source = InputSource()
input_source.setByteStream(input)
xml_reader = xml.sax.make_parser()
xml_reader.setContentHandler(SVGHandler(self))
xml_reader.setErrorHandler(error_handler)
xml_reader.setEntityResolver(entity_resolver)
xml_reader.setDTDHandler(dtd_handler)
xml_reader.setFeature(handler.feature_external_ges, False)
xml_reader.parse(input_source)
input.close
self.end_all()
if self.page_layout:
self.object.load_SetLayout(self.page_layout)
self.object.load_Completed()
return self.object
except:
warn_tb('INTERNAL')
raise
开发者ID:DDRBoxman,项目名称:Spherebot-Host-GUI,代码行数:31,代码来源:svgloader.py
示例11: _build_model
def _build_model(self):
content_handler = XMLDocReader(self.presenter)
error_handler = ErrorHandler()
entity_resolver = EntityResolver()
dtd_handler = DTDHandler()
try:
filename = os.path.join(self.presenter.doc_dir, 'content.xml')
handler = open(filename, 'r')
lines = float(sum(1 for l in handler))
handler.close()
self.file_handler = open(filename, "r")
input_source = InputSource()
input_source.setByteStream(self.file_handler)
content_handler.lines = lines
xml_reader = xml.sax.make_parser()
xml_reader.setContentHandler(content_handler)
xml_reader.setErrorHandler(error_handler)
xml_reader.setEntityResolver(entity_resolver)
xml_reader.setDTDHandler(dtd_handler)
xml_reader.parse(input_source)
self.file_handler.close()
content_handler.file = None
except:
errtype, value, traceback = sys.exc_info()
msg = _('It seems content.xml is corrupted') + '\n' + value
events.emit(events.MESSAGES, msgconst.ERROR, msg)
raise IOError(errtype, msg , traceback)
self.model = content_handler.model
msg = _('Content.xml is parsed successfully')
events.emit(events.MESSAGES, msgconst.OK, msg)
开发者ID:Scrik,项目名称:sk1-wx,代码行数:31,代码来源:pdxf_filters.py
示例12: load
def load(odffile):
from load import LoadParser
from xml.sax import make_parser, handler
z = zipfile.ZipFile(odffile)
mimetype = z.read('mimetype')
doc = OpenDocument(mimetype, add_generator=False)
# Look in the manifest file to see if which of the four files there are
manifestpart = z.read('META-INF/manifest.xml')
manifest = manifestlist(manifestpart)
for xmlfile in ('settings.xml', 'meta.xml', 'content.xml', 'styles.xml'):
if not manifest.has_key(xmlfile):
continue
try:
xmlpart = z.read(xmlfile)
doc._parsing = xmlfile
parser = make_parser()
parser.setFeature(handler.feature_namespaces, 1)
parser.setContentHandler(LoadParser(doc))
parser.setErrorHandler(handler.ErrorHandler())
inpsrc = InputSource()
inpsrc.setByteStream(StringIO(xmlpart))
parser.parse(inpsrc)
del doc._parsing
except KeyError, v: pass
# FIXME: Add subobjects correctly here
for mentry,mvalue in manifest.items():
if mentry[:9] == "Pictures/" and len(mentry) > 9:
doc.addPicture(mvalue['full-path'], mvalue['media-type'], z.read(mentry))
elif mentry == "Thumbnails/thumbnail.png":
doc.addThumbnail(z.read(mentry))
elif mentry in ('settings.xml', 'meta.xml', 'content.xml', 'styles.xml'):
pass
else:
if mvalue['full-path'][-1] == '/':
doc._extra.append(OpaqueObject(mvalue['full-path'], mvalue['media-type'], None))
else:
doc._extra.append(OpaqueObject(mvalue['full-path'], mvalue['media-type'], z.read(mentry)))
# Add the SUN junk here to the struct somewhere
# It is cached data, so it can be out-of-date
z.close()
b = doc.getElementsByType(Body)
if mimetype[:39] == 'application/vnd.oasis.opendocument.text':
doc.text = b[0].firstChild
elif mimetype[:43] == 'application/vnd.oasis.opendocument.graphics':
doc.graphics = b[0].firstChild
elif mimetype[:47] == 'application/vnd.oasis.opendocument.presentation':
doc.presentation = b[0].firstChild
elif mimetype[:46] == 'application/vnd.oasis.opendocument.spreadsheet':
doc.spreadsheet = b[0].firstChild
elif mimetype[:40] == 'application/vnd.oasis.opendocument.chart':
doc.chart = b[0].firstChild
elif mimetype[:40] == 'application/vnd.oasis.opendocument.image':
doc.image = b[0].firstChild
elif mimetype[:42] == 'application/vnd.oasis.opendocument.formula':
doc.formula = b[0].firstChild
return doc
开发者ID:kiniou,项目名称:blender-smooth-slides,代码行数:59,代码来源:opendocument.py
示例13: test_character_stream
def test_character_stream(self):
# If the source is an InputSource with a character stream, use it.
src = InputSource(self.file)
src.setCharacterStream(self.make_character_stream())
prep = prepare_input_source(src)
self.assertIsNone(prep.getByteStream())
self.checkContent(prep.getCharacterStream(),
"This is a character stream.")
开发者ID:Eyepea,项目名称:cpython,代码行数:8,代码来源:test_sax.py
示例14: test_parse_InputSource
def test_parse_InputSource(self):
# accept data without declared but with explicitly specified encoding
make_xml_file(self.data, 'iso-8859-1', None)
with open(TESTFN, 'rb') as f:
input = InputSource()
input.setByteStream(f)
input.setEncoding('iso-8859-1')
self.check_parse(input)
开发者ID:Eyepea,项目名称:cpython,代码行数:8,代码来源:test_sax.py
示例15: parse_request
def parse_request(self,soap_body,sinfo,encoding):
parser = make_parser()
ch = SOAP11ContentHandler(parser)
parser.setContentHandler(ch)
inpsrc = InputSource()
inpsrc.setByteStream(BytesIO(soap_body))
parser.parse(inpsrc)
return ch.req_dict
开发者ID:JoneXiong,项目名称:PyWebSV,代码行数:8,代码来源:soap11.py
示例16: resolveEntity
def resolveEntity(self, publicId, systemId):
for p in self.path:
fname = os.path.join(p, systemId)
if os.path.exists(fname):
source = InputSource(systemId)
source.setByteStream(open(fname))
return source
return InputSource(systemId)
开发者ID:AnujaLK,项目名称:andes,代码行数:8,代码来源:__init__.py
示例17: test_byte_stream
def test_byte_stream(self):
# If the source is an InputSource that does not have a character
# stream but does have a byte stream, use the byte stream.
src = InputSource(self.file)
src.setByteStream(self.make_byte_stream())
prep = prepare_input_source(src)
self.assertIsNone(prep.getCharacterStream())
self.checkContent(prep.getByteStream(),
b"This is a byte stream.")
开发者ID:Eyepea,项目名称:cpython,代码行数:9,代码来源:test_sax.py
示例18: parse
def parse(self) :
if (isinstance(self.source,unicode)) :
# Create a string source
file = io.StringIO(self.source)
input = InputSource(file)
input.setEncoding("utf-8")
input.setCharacterStream(file)
# There is a bug in xml.sax.saxutils.prepare_input_source
input.setByteStream(file)
input.setSystemId(None)
elif (isinstance(self.source,InputSource)):
input = self.source
else:
raise Exception("Parse source must be either string or InputSource")
# Create the parser/xmlreader
parser = xml.sax.make_parser()
# Tell the parser to use our handler(s)
parser.setContentHandler(self)
#parser.setErrorHandler(self)
#parser.setFeature(xml.sax.handler.feature_namespaces,True)
# Shut off dtd validation
parser.setFeature(xml.sax.handler.feature_validation,False)
parser.setFeature(xml.sax.handler.feature_external_ges, False)
# Parse the document
parser.parse(input)
开发者ID:DennisHeimbigner,项目名称:yax,代码行数:29,代码来源:saxeventhandler.py
示例19: test_expat_inpsource_location
def test_expat_inpsource_location():
parser = make_parser()
parser.setContentHandler(ContentHandler()) # do nothing
source = InputSource()
source.setByteStream(StringIO("<foo bar foobar>")) #ill-formed
name = "a file name"
source.setSystemId(name)
try:
parser.parse(source)
except SAXException, e:
return e.getSystemId() == name
开发者ID:Birdbird,项目名称:StartPage,代码行数:11,代码来源:test_sax2.py
示例20: test_expat_inpsource_stream
def test_expat_inpsource_stream():
parser = make_parser()
result = StringIO()
xmlgen = XMLGenerator(result)
parser.setContentHandler(xmlgen)
inpsrc = InputSource()
inpsrc.setByteStream(open(findfile("test.xml")))
parser.parse(inpsrc)
return result.getvalue() == xml_test_out
开发者ID:Birdbird,项目名称:StartPage,代码行数:11,代码来源:test_sax2.py
注:本文中的xml.sax.xmlreader.InputSource类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论