本文整理汇总了Python中xmldict.xml_to_dict函数的典型用法代码示例。如果您正苦于以下问题:Python xml_to_dict函数的具体用法?Python xml_to_dict怎么用?Python xml_to_dict使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了xml_to_dict函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: test_xml_to_dict_strict
def test_xml_to_dict_strict(self):
test = """
<payment_method>
<created_at type="datetime">2011-02-12T20:20:46Z</created_at>
<is_retained type="boolean">true</is_retained>
<messages>
<message class="error" context="input.cvv" key="too_long" />
<message class="error" context="input.card_number" key="failed_checksum" />
</messages>
</payment_method>
"""
expected = {
"payment_method": {
"created_at": {
"@type": "datetime",
"#value": datetime.datetime(2011, 2, 12, 20, 20, 46),
"#text": "2011-02-12T20:20:46Z",
},
"is_retained": {"@type": "boolean", "#value": True, "#text": "true"},
"messages": {
"message": [
{"@class": "error", "@context": "input.cvv", "@key": "too_long"},
{"@class": "error", "@context": "input.card_number", "@key": "failed_checksum"},
]
},
}
}
self.assertEqual(expected, xml_to_dict(test, strict=True))
开发者ID:sintrb,项目名称:xmldict,代码行数:30,代码来源:tests.py
示例2: get_house_roll_call_vote_data
def get_house_roll_call_vote_data(congress_number):
data = []
opener = urllib2.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
session_number = 1
while session_number < 3:
roll_number = 1
while True:
try:
url = _get_house_roll_call_vote_data_url(congress_number, session_number, roll_number)
response = opener.open(url)
vote_data = response.read()
# some redirect mechanism has blocked the HTTP error from happenning
# special treatment made using the redirected-page to jump out of the loop
if re.search('<!DOCTYPE html', vote_data):
# usually an XML is rendered, but if the url is not valid
# webpage is redirected to an html page
break
# data.append(_get_formatted_vote_data(vote_data))
dict = xmldict.xml_to_dict(vote_data)
data.append(dict)
roll_number += 1
except urllib2.HTTPError:
print 'HTTP error occurred at ' + url
session_number += 1
return data
开发者ID:YangLiu928,项目名称:NDP_Projects,代码行数:26,代码来源:house_vote_to_JSON.py
示例3: response_to_dict
def response_to_dict(self,response,return_format):
response_dict = {}
json_match = re.search('^\s*{', response)
xml_match = re.search('^\s*\<', response)
ini_match = re.search('^\s*\[', response)
if json_match :
self.log.info(" Response is in 'JSON' format and Converting to '"+return_format+"' format")
# Formatting the json string
response = re.sub(r"{\s*'?(\w)", r'{"\1', response)
response = re.sub(r",\s*'?(\w)", r',"\1', response)
response = re.sub(r"(\w)'?\s*:", r'\1":', response)
response = re.sub(r":\s*'(\w)'\s*([,}])", r':"\1"\2', response)
try :
import json
response_dict = json.loads(response)
except StandardError:
self.log.exception( "Json Parser is unable to parse the string" )
return response_dict
elif ini_match :
self.log.info(" Response is in 'INI' format and Converting to '"+return_format+"' format")
from configobj import ConfigObj
response_file = open("respnse_file.temp",'w')
response_file.write(response)
response_file.close()
response_dict = ConfigObj("respnse_file.temp")
return response_dict
elif xml_match :
self.log.info(" Response is in 'XML' format and Converting to '"+return_format+"' format")
try :
response_dict = xmldict.xml_to_dict("<response> "+str(response)+" </response>")
except StandardError:
self.log.exception()
return response_dict
开发者ID:rainkinste,项目名称:OnosSystemTest,代码行数:33,代码来源:teston.py
示例4: test_xml_to_dict_strict
def test_xml_to_dict_strict(self):
test = '''
<payment_method>
<created_at type="datetime">2011-02-12T20:20:46Z</created_at>
<is_retained type="boolean">true</is_retained>
<messages>
<message class="error" context="input.cvv" key="too_long" />
<message class="error" context="input.card_number" key="failed_checksum" />
</messages>
</payment_method>
'''
expected = {'payment_method': {
'created_at': {
'@type': 'datetime',
'#value': datetime.datetime(2011, 2, 12, 20, 20, 46),
'#text': '2011-02-12T20:20:46Z'
},
'is_retained': {
'@type': 'boolean',
'#value': True,
'#text': 'true'
},
'messages': {'message': [{'@class': 'error',
'@context': 'input.cvv',
'@key': 'too_long'},
{'@class': 'error',
'@context': 'input.card_number',
'@key': 'failed_checksum'}]},
}}
self.assertEqual(expected, xml_to_dict(test, strict=True))
开发者ID:kowalpy,项目名称:xmldict,代码行数:32,代码来源:tests.py
示例5: upload_metadata
def upload_metadata(self, project, raw_metadata):
''' upload xml or json to the metadata server'''
headers = {}
headers.update(self.headers)
try:
file_type = magic.from_buffer(raw_metadata[:200])
if file_type == "XML document text":
#headers["content-type"] = "xml"
metadata = xmldict.xml_to_dict(raw_metadata)["ResultSet"]["Result"]
except Exception:
metadata = raw_metadata
#else:
# metadata = json.loads(raw_metadata)
path = "%s%s%s" % (self.id_service, self.METADATA_PATH, project)
with SourceInterface(self.interface):
chunk_size = 1024
ids = []
for start in range(0, len(metadata), chunk_size):
response = requests.put(path, data=json.dumps(
metadata[start: start + chunk_size]), headers=headers)
if "x-id-auth-token" in response.headers:
self.headers["x-id-auth-token"] = response.headers[
"x-id-auth-token"]
ids.append(response.text)
return ids
开发者ID:LabAdvComp,项目名称:tukey_middleware,代码行数:27,代码来源:client.py
示例6: queryStation
def queryStation(sID):
api_key = "UPIIJBD0QEG"
url = "http://api.rideuta.com/SIRI/SIRI.svc/"
url += "StopMonitor?stopid=" # Query type
url += sID # Stop ID
url += "&minutesout=20" # How far in the future to query
url += "&onwardcalls=false" # Include vehicle calls inbetween current location and stop
url += "&filterroute=" # Filter vehicles
url += "&usertoken="
url += api_key
r = requests.get(url)
xml = r.content
d = xmldict.xml_to_dict(xml)
d2 = d['{http://www.siri.org.uk/siri}Siri']['{http://www.siri.org.uk/siri}StopMonitoringDelivery']['{http://www.siri.org.uk/siri}MonitoredStopVisit']['{http://www.siri.org.uk/siri}MonitoredVehicleJourney']
if '{http://www.siri.org.uk/siri}MonitoredVehicleJourney' not in d['{http://www.siri.org.uk/siri}Siri']['{http://www.siri.org.uk/siri}StopMonitoringDelivery']['{http://www.siri.org.uk/siri}MonitoredStopVisit']:
print "Uh Oh!"
else:
# Print Query Header
localtime = time.asctime(time.localtime(time.time()))
print ("\nQUERY STATION: %s \n" % colored.black(d['{http://www.siri.org.uk/siri}Siri']['{http://www.siri.org.uk/siri}StopMonitoringDelivery']['{http://www.siri.org.uk/siri}Extensions']['{http://www.siri.org.uk/siri}StopName']))
print "Query Time: %s /n" % str(localtime)
getData(nStopID, 0)
getData(sStopID, 1)
开发者ID:Austintrujillo1,项目名称:uta,代码行数:28,代码来源:uta.py
示例7: set_xml
def set_xml(self, input):
result = xml_to_dict(input)
for k, v in result.iteritems():
if k != 'id' and k in self.getFields():
setattr(self, k, v)
elif k == 'id':
self._id = v
开发者ID:whyzgeek,项目名称:web2py-dal-plus-bottle,代码行数:7,代码来源:model.py
示例8: parseProductXmlAndStore
def parseProductXmlAndStore():
tcgOutputFile = open(os.path.join(PROJECT_ROOT, 'tcgoutput.xml'))
#print(tcgOutputFile)
#print(tcgOutputFile.read())
tcgOutputString = tcgOutputFile.read();
#print(tcgOutputString)
tcgXml = ET.fromstring(tcgOutputString)
#print tcgXml
tcgDictList = []
for child in tcgXml:
#print child
tcgDictList.append(xmldict.xml_to_dict(child))
#print tcgDictList[1]
# tcgOutputDict = xmldict.xml_to_dict(tcgOutputString)
# print(tcgOutputDict)
# productArray = tcgOutputDict['products']['product']
# print(productArray)
# for product in productArray:
# print product['id']
productList = []
for tcgDict in tcgDictList:
prod = Product.create(tcgDict['product'])
productList.append(prod)
#print productList[0].tcgId
return productList
开发者ID:insanetheta,项目名称:mysticaltutor,代码行数:25,代码来源:productFetcher.py
示例9: list_keys
def list_keys(self):
""" List the keys, libcloud didn't work so we had to fetch some xml"""
aws_schema = "http://ec2.amazonaws.com/doc/2010-08-31/"
xml_as_dict = xmldict.xml_to_dict(
self.conn.connection.request(self.conn.path, params={"Action": "DescribeKeyPairs"})
.__dict__["body"]
.replace(aws_schema, "")
)
if xml_as_dict["DescribeKeyPairsResponse"]["keySet"] is None:
return "[]"
else:
result = xml_as_dict["DescribeKeyPairsResponse"]["keySet"]["item"]
if "keyName" in result:
result["keyMaterial"] = ""
result = [result]
else:
for item in result:
if "keyName" in result:
item["keyMaterial"] = ""
if self.options.id:
result = keypair_by_name(self.options.id, result)
keys_json = json.dumps(result)
return keys_json
开发者ID:occ-data,项目名称:tukey-middleware,代码行数:26,代码来源:compute.py
示例10: get_senate_roll_call_vote
def get_senate_roll_call_vote(congress_number):
# compare
web_structure_has_changed = _check_web_structure(_get_senate_roll_call_vote_url(congress_number, 1, 1),
WEB_STRUCTURE_FINGER_PRINT)
if web_structure_has_changed:
print 'the web structure has changed, we need to modify our code to adapt to the changes'
return [None, None]
# the function is meant to return the senate vote data as an array of dictionaries
# The index of a specific vote data is vote_number - 1 due to zero based indexing system
dictionaries = []
# this opener adds a header to the HTTP requests, and mimic the behavior of a browser
# in order to avoid 503 service not available error
opener = urllib2.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
# each congress has no more than 2 sessions
session_number = 1
while session_number < 3:
# re-basing the vote number
vote_number = 1
while True:
try:
url = _get_senate_roll_call_vote_url(congress_number, session_number, vote_number)
# print url
# dictionary=xmldict.xml_to_dict(requests.get(url).content)
response = opener.open(url)
dictionary = xmldict.xml_to_dict(response.read())
internal_ids = _get_internal_ids(dictionary)
dictionary['ndp_specs'] = {'internal_id': internal_ids[0], 'amendment_to_id': internal_ids[1]}
vote_number += 1
dictionaries.append(dictionary)
except urllib2.HTTPError:
# either the vote number has incremented high enough, or some unknown url error occurred
break
session_number += 1
return dictionaries
开发者ID:YangLiu928,项目名称:NDP_Projects,代码行数:35,代码来源:senate_vote_to_JSON.py
示例11: read
def read(self):
result = {}
tree = ET.tostring( self.xml[ len(self.xml) - 1 ] )
result['deputado'] = xmldict.xml_to_dict(tree)
return result
开发者ID:henriquebastos,项目名称:deputados,代码行数:8,代码来源:webservices.py
示例12: getFeed
def getFeed(self):
data = []
for podcast in self.opt['podcasts']:
get = urllib2.urlopen(podcast).read()
xml = xmldict.xml_to_dict(get)
data += xml['rss']['channel']['item']
return data
开发者ID:KartikTalwar,项目名称:Podmon,代码行数:9,代码来源:podcasts.py
示例13: convert
def convert():
'''Loads the cards.xml file, converts to JSON, and saves it'''
#Load the cards file, make sure it exists
try:
cards = open('cards.xml')
except IOError:
print 'No cards.xml file defined! Make sure cards.xml exists'
return False
#Read the file
cards = cards.read()
#Convert the sucker
cards_dict = xmldict.xml_to_dict(cards)
#Prepare json file
json_file = open('cards.json', 'w')
#Get the cards
cards = cards_dict['cockatrice_carddatabase']['cards']['card']
#MongoDB expects the JSON file to have one document per line, so we need to
# iterate over each line in the file
for card in cards:
#Lets add some extra info to the card object
# Store power and toughness separately as ints
i=0
for type in ['power', 'toughness']:
try:
card[type] = card['pt'].split('/')[i]
try:
#try to turn to int. It may not be an int
# (in case of X)
# pt is always X/Y, so split on / and use 0 index
# for power and 1 for toughness
card[type] = int(card['pt'].split('/')[i])
except ValueError:
pass
except (KeyError, IndexError) as e:
#card has no power or toughness
pass
#keep track of what item we're on
i = i+1
#Also save the set name as a key so we don't have to access the set
# key to get the set text
card['setText'] = card['set']['#text']
#Save it
json_file.write(json.dumps(card) + '\n')
#close it
json_file.close()
return True
开发者ID:erikhazzard,项目名称:DeckViz,代码行数:56,代码来源:convert_cards_to_json.py
示例14: test_xml_to_dict
def test_xml_to_dict(self):
test = '''
<payment_method>
<payment_method_token>QhLaMNNpvHwfnFbHbUYhNxadx4C</payment_method_token>
<created_at type="datetime">2011-02-12T20:20:46Z</created_at>
<updated_at type="datetime">2011-04-22T17:57:30Z</updated_at>
<custom>Any value you want us to save with this payment method.</custom>
<is_retained type="boolean">true</is_retained>
<is_redacted type="boolean">false</is_redacted>
<is_sensitive_data_valid type="boolean">false</is_sensitive_data_valid>
<messages>
<message class="error" context="input.cvv" key="too_long" />
<message class="error" context="input.card_number" key="failed_checksum" />
</messages>
<last_four_digits>1111</last_four_digits>
<card_type>visa</card_type>
<first_name>Bob</first_name>
<last_name>Smith</last_name>
<expiry_month type="integer">1</expiry_month>
<expiry_year type="integer">2020</expiry_year>
<address_1 nil="true"></address_1>
<address_2 nil="true"></address_2>
<city nil="true"></city>
<state nil="true"></state>
<zip nil="true"></zip>
<country nil="true"></country>
</payment_method>
'''
expected = {'payment_method': {'address_1': {'nil': 'true'},
'address_2': {'nil': 'true'},
'card_type': 'visa',
'city': {'nil': 'true'},
'country': {'nil': 'true'},
'created_at': datetime.datetime(2011, 2, 12, 20, 20, 46),
'custom': 'Any value you want us to save with this payment method.',
'expiry_month': 1,
'expiry_year': 2020,
'first_name': 'Bob',
'is_redacted': False,
'is_retained': True,
'is_sensitive_data_valid': False,
'last_four_digits': '1111',
'last_name': 'Smith',
'messages': {'message': [{'class': 'error',
'context': 'input.cvv',
'key': 'too_long'},
{'class': 'error',
'context': 'input.card_number',
'key': 'failed_checksum'}]},
'payment_method_token': 'QhLaMNNpvHwfnFbHbUYhNxadx4C',
'state': {'nil': 'true'},
'updated_at': datetime.datetime(2011, 4, 22, 17, 57, 30),
'zip': {'nil': 'true'}}}
self.assertEqual(expected, xml_to_dict(test))
开发者ID:kagesenshi,项目名称:xmldict,代码行数:56,代码来源:tests.py
示例15: test_xml_to_dict_list
def test_xml_to_dict_list(self):
test = """
<messages>
<message>message1</message>
<message>message2</message>
</messages>
"""
expected = {"messages": {"message": ["message1", "message2"]}}
self.assertEqual(expected, xml_to_dict(test, strict=False))
开发者ID:sintrb,项目名称:xmldict,代码行数:10,代码来源:tests.py
示例16: test_xml_to_dict_list
def test_xml_to_dict_list(self):
test = '''
<messages>
<message>message1</message>
<message>message2</message>
</messages>
'''
expected = {'messages': {'message': ['message1', 'message2']}}
self.assertEqual(expected, xml_to_dict(test, strict=False))
开发者ID:kowalpy,项目名称:xmldict,代码行数:10,代码来源:tests.py
示例17: test_xml_to_dict_namespace
def test_xml_to_dict_namespace(self):
xml_str1 = """<root id="1" xmlns="somenamespace"><items><item>1</item><item>2</item></items></root>"""
xml_str2 = """<root id="1"><items><item>1</item><item>2</item></items></root>"""
expected1 = {'{somenamespace}root': {'{somenamespace}items': {'{somenamespace}item': ['1', '2']}}}
expected2 = {'root': {'items': {'item': ['1', '2']}}}
self.assertEqual(expected1, xml_to_dict(xml_str1, strict=False))
self.assertEqual(expected1, xml_to_dict(xml_str1))
self.assertEqual(expected2, xml_to_dict(xml_str1, False, True))
self.assertEqual(expected2, xml_to_dict(xml_str1, remove_namespace=True))
self.assertEqual(expected2, xml_to_dict(xml_str2, strict=False))
self.assertEqual(expected2, xml_to_dict(xml_str2))
self.assertEqual(expected2, xml_to_dict(xml_str2, False, True))
self.assertEqual(expected2, xml_to_dict(xml_str2, remove_namespace=True))
开发者ID:kowalpy,项目名称:xmldict,代码行数:13,代码来源:tests.py
示例18: configparser
def configparser(self):
'''
It will parse the config file (teston.cfg) and return as dictionary
'''
matchFileName = re.match(r'(.*)\.cfg', self.configFile, re.M | re.I)
if matchFileName:
xml = open(self.configFile).read()
try :
self.configDict = xmldict.xml_to_dict(xml)
return self.configDict
except Exception:
print "There is no such file to parse " + self.configFile
开发者ID:zhanghaoyu7,项目名称:OnosSystemTest,代码行数:12,代码来源:teston.py
示例19: getKeywords
def getKeywords(text):
# Set params for keyword search
params = AlchemyAPI.AlchemyAPI_KeywordParams()
params.setMaxRetrieve(30)
params.setKeywordExtractMode('strict')
if isinstance(text, unicode):
text = unicodedata.normalize('NFKD', text).encode('ascii', 'ignore')
result = xml_to_dict(alchemyObj.TextGetRankedKeywords(text, params))
try:
keywords = result['results']['keywords']['keyword']
except:
keywords = []
return keywords
开发者ID:figpope,项目名称:alchemy,代码行数:14,代码来源:docParse.py
示例20: getConcepts
def getConcepts(text):
# Set params for keyword search
params = AlchemyAPI.AlchemyAPI_ConceptParams()
params.setMaxRetrieve(30)
if isinstance(text, unicode):
text = unicodedata.normalize('NFKD', text).encode('ascii', 'ignore')
result = xml_to_dict(alchemyObj.TextGetRankedConcepts(text, params))
keywords = result['results']['concepts']['concept']
temp = []
for result in keywords:
temp.append({'relevance': result['relevance'], 'text': result['text']})
keywords = temp
return keywords
开发者ID:figpope,项目名称:alchemy,代码行数:14,代码来源:docParse.py
注:本文中的xmldict.xml_to_dict函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论