Skip to content

Commit 69fd221

Browse files
author
MarkDavidson
committed
Updated _stringify_content
1 parent 2b4775c commit 69fd221

File tree

1 file changed

+26
-2
lines changed

1 file changed

+26
-2
lines changed

libtaxii/messages.py

+26-2
Original file line numberDiff line numberDiff line change
@@ -775,10 +775,34 @@ def timestamp_label(self, value):
775775
self._timestamp_label = value
776776

777777
def _stringify_content(self, content):
778-
"""Always a string or raises an error."""
778+
"""Always a string or raises an error.
779+
Returns the string representation and whether the data is XML.
780+
"""
781+
#If it's an etree, it's definitely XML
779782
if isinstance(content, etree._ElementTree) or isinstance(content, etree._Element):
780783
return etree.tostring(content), True
781-
784+
785+
#It might be a string representation of XML
786+
#There is an edge case here where a string that looks like XML
787+
# (e.g., '<Hello/>') but isn't actually XML (and, honestly, in the
788+
# string representation the difference is somewhat academic)
789+
# will get interpreted as XML.
790+
try:
791+
etree.parse(content, get_xml_parser())
792+
return str(content), True
793+
except IOError:#This error happens if the content is not a file-like object (e.g., StringIO.StringIO)
794+
pass
795+
except etree.XMLSyntaxError:#This happens when it is a file like object, but does not contain well formed XML
796+
pass
797+
798+
try:
799+
sio_content = StringIO.StringIO(content)
800+
etree.parse(sio_content, get_xml_parser())
801+
return str(content), True
802+
except etree.XMLSyntaxError:#This happens if the content is not well formed XML
803+
pass
804+
805+
#The default is that it's not XML
782806
return str(content), False
783807

784808
def to_etree(self):

0 commit comments

Comments
 (0)