我正在使用xmltodict来解析XML配置.XML具有一个结构,其中元素可以在1到n个实例中出现,其中两个都是有效的:
<items>
<item-ref>abc</item-ref>
</items>
Run Code Online (Sandbox Code Playgroud)
和
<items>
<item-ref>abc</item-ref>
<item-ref>dca</item-ref>
<item-ref>abb</item-ref>
</items>
Run Code Online (Sandbox Code Playgroud)
我用xmltodict解析这个如下:
document['items']['item-ref']
Run Code Online (Sandbox Code Playgroud)
并且它返回单个unicode或列表(取决于找到的项目),所以我总是需要添加额外的检查以确保我是否需要处理列表或字符串:
if isinstance(document['items']['item-ref'], list):
my_var = document['items']['item-ref']
else:
my_var = [document['items']['item-ref']] #create list manually
Run Code Online (Sandbox Code Playgroud)
是否有更好/更简单/更优雅的方式来处理这些?
我试图轻松访问xml文件中的值.
<artikelen>
<artikel nummer="121">
<code>ABC123</code>
<naam>Highlight pen</naam>
<voorraad>231</voorraad>
<prijs>0.56</prijs>
</artikel>
<artikel nummer="123">
<code>PQR678</code>
<naam>Nietmachine</naam>
<voorraad>587</voorraad>
<prijs>9.99</prijs>
</artikel>
..... etc
Run Code Online (Sandbox Code Playgroud)
如果我想访问值ABC123,我该如何获取它?
import xmltodict
with open('8_1.html') as fd:
doc = xmltodict.parse(fd.read())
print(doc[fd]['code'])
Run Code Online (Sandbox Code Playgroud) 我xmltodict用来解析xml.
如果我们解析无效的xml,它会抛出一个ExpatError.
我怎么抓住这个?这是我在ipython shell中尝试过的
>>> import xmltodict
>>> xml_data = """<?xml version="1.0" encoding="UTF-8" ?>
... <Website>"""
>>> xml_dict = xmltodict.parse(xml_data)
ExpatError: no element found
>>> try:
... xml_dict = xmltodict.parse(xml_data)
... except ExpatError:
... print "that's right"
NameError: name 'ExpatError' is not defined
>>> try:
... xml_dict = xmltodict.parse(xml_data)
... except xmltodict.ExpatError:
... print "that's right"
AttributeError: 'module' object has no attribute 'ExpatError'
Run Code Online (Sandbox Code Playgroud) 如果"车库"中只有一个"汽车",则以下代码会产生错误:
import xmltodict
mydict = xmltodict.parse(xmlstringResults)
for carsInGarage in mydict['garage']['car']:
# do something...
Run Code Online (Sandbox Code Playgroud)
原因是mydict['garage']['car']只有一个列表,如果有一个以上的"汽车"元素.所以我做了这样的事情:
import xmltodict
mydict = xmltodict.parse(xmlstringResults)
if isinstance(mydict['garage']['car'], list):
for carsInGarage in mydict['garage']['car']:
# do something for each car...
else:
# do something for the car
Run Code Online (Sandbox Code Playgroud)
让代码运行.但对于更高级的操作,这不是解决方案.
有人知道某种功能,即使只有一个元素吗?
对于 Python 来说相对较新,我使用 Pipenv 创建了一个项目,该项目使用 xmltodict 模块。我看过一些类似的问题,但找不到我需要做什么。
我已经使用 pipelinenv 安装 xmltodict 模块,但仍然收到以下错误:
Traceback (most recent call last):
File "./storagereport.py", line 12, in <module>
import xmltodict
ImportError: No module named 'xmltodict'
Run Code Online (Sandbox Code Playgroud)
Pipenv 显示模块已安装:
$ pipenv graph
xmltodict==0.12.0
Run Code Online (Sandbox Code Playgroud)
有人可以帮忙吗?
我有一个xml表格的文件:
<NewDataSet>
<Root>
<Phonemic>and</Phonemic>
<Phonetic>nd</Phonetic>
<Description/>
<Start>0</Start>
<End>8262</End>
</Root>
<Root>
<Phonemic>comfortable</Phonemic>
<Phonetic>comfetebl</Phonetic>
<Description>adj</Description>
<Start>61404</Start>
<End>72624</End>
</Root>
</NewDataSet>
Run Code Online (Sandbox Code Playgroud)
我需要处理它,例如,当用户输入时nd,程序将其与<Phonetic>标签匹配并and从<Phonemic>零件返回.我想也许如果我可以将xml文件转换为字典,我将能够迭代数据并在需要时查找信息.
我搜索并找到了用于相同目的的xmltodict:
import xmltodict
with open(r'path\to\1.xml', encoding='utf-8', errors='ignore') as fd:
obj = xmltodict.parse(fd.read())
Run Code Online (Sandbox Code Playgroud)
运行这个给了我一个ordered dict:
>>> obj
OrderedDict([('NewDataSet', OrderedDict([('Root', [OrderedDict([('Phonemic', 'and'), ('Phonetic', 'nd'), ('Description', None), ('Start', '0'), ('End', '8262')]), OrderedDict([('Phonemic', 'comfortable'), ('Phonetic', 'comfetebl'), ('Description', 'adj'), ('Start', '61404'), ('End', '72624')])])]))])
Run Code Online (Sandbox Code Playgroud)
现在不幸的是,这并没有使事情变得更简单,我不确定如何使用新的数据结构来实现程序.例如要访问nd我必须写:
obj['NewDataSet']['Root'][0]['Phonetic']
Run Code Online (Sandbox Code Playgroud)
这太荒谬了.我试图把它变成一个普通的字典,dict()但由于它是嵌套的,内层保持有序,我的数据是如此之大.
我有这个XML文件:
<?xml version="1.0"?>
<toolbox tool_path="/galaxy/main/shed_tools">
<section id="snpeff" name="snpEff" version="">
<tool file="toolshed.g2.bx.psu.edu/repos/pcingola/snpeff/c052639fa666/snpeff/snpEff_2_1a/snpEff_2_1a/galaxy/snpSift_filter.xml" guid="toolshed.g2.bx.psu.edu/repos/pcingola/snpeff/snpSift_filter/1.0">
<tool_shed>toolshed.g2.bx.psu.edu</tool_shed>
<repository_name>snpeff</repository_name>
<repository_owner>pcingola</repository_owner>
<installed_changeset_revision>c052639fa666</installed_changeset_revision>
<id>toolshed.g2.bx.psu.edu/repos/pcingola/snpeff/snpSift_filter/1.0</id>
<version>1.0</version>
</tool>
<tool file="toolshed.g2.bx.psu.edu/repos/pcingola/snpeff/c052639fa666/snpeff/snpEff_2_1a/snpEff_2_1a/galaxy/snpEff.xml" guid="toolshed.g2.bx.psu.edu/repos/pcingola/snpeff/snpEff/1.0">
<tool_shed>toolshed.g2.bx.psu.edu</tool_shed>
<repository_name>snpeff</repository_name>
<repository_owner>pcingola</repository_owner>
<installed_changeset_revision>c052639fa666</installed_changeset_revision>
<id>toolshed.g2.bx.psu.edu/repos/pcingola/snpeff/snpEff/1.0</id>
<version>1.0</version>
</tool>
<tool file="toolshed.g2.bx.psu.edu/repos/gregory-minevich/check_snpeff_candidates/22c8c4f8d11c/check_snpeff_candidates/checkSnpEffCandidates.xml" guid="toolshed.g2.bx.psu.edu/repos/gregory-minevich/check_snpeff_candidates/check_snpeff_candidates/1.0.0">
<tool_shed>toolshed.g2.bx.psu.edu</tool_shed>
<repository_name>check_snpeff_candidates</repository_name>
<repository_owner>gregory-minevich</repository_owner>
<installed_changeset_revision>22c8c4f8d11c</installed_changeset_revision>
<id>toolshed.g2.bx.psu.edu/repos/gregory-minevich/check_snpeff_candidates/check_snpeff_candidates/1.0.0</id>
<version>1.0.0</version>
</tool>
</section>
...
Run Code Online (Sandbox Code Playgroud)
我试图通过以下方式解析上面的文件:
import xmltodict
# wget -c https://raw.githubusercontent.com/galaxyproject/usegalaxy-playbook/c55aa042825fe02ef4a02d958eb811adba8ea45f/files/galaxy/usegalaxy.org/var/shed_tool_conf.xml
if __name__ == '__main__':
with open('tests/shed_tool_conf.xml') as fd:
doc = xmltodict.parse(fd.read())
tools_section = doc['toolbox']['section']['@name']
print tools_section
Run Code Online (Sandbox Code Playgroud)
但是,我有以下错误:
Traceback (most recent call last):
File "importTools2Galaxy.py", line 15, in <module>
tools_section = …Run Code Online (Sandbox Code Playgroud) 我使用xmltodict进行 XML 解析/解解析,并且需要在处理一个文档时保留 XML 元素顺序。玩具 REPL 示例:
>>> import xmltodict
>>> xml = """
... <root>
... <a />
... <b />
... <a />
... </root>
... """
>>> xmltodict.parse(xml)
OrderedDict([('root', OrderedDict([('a', [None, None]), ('b', None)]))])
>>> xmltodict.unparse(_)
'<?xml version="1.0" encoding="utf-8"?>\n<root><a></a><a></a><b></b></root>'
Run Code Online (Sandbox Code Playgroud)
请注意,原始序列[a, b, a]已替换为[a, a, b]。有什么办法可以保留原始订单吗xmltodict?
我试图使用xmltodict从输入xml文件创建一个json文件,代码如下
import io, xmltodict, json
infile = io.open(filename_xml, 'r')
outfile = io.open(filename_json, 'w')
o = xmltodict.parse( infile.read() )
json.dump( o , outfile )
Run Code Online (Sandbox Code Playgroud)
最后一行给我带来以下错误
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 182, in dump
fp.write(chunk)
TypeError: must be unicode, not str
Run Code Online (Sandbox Code Playgroud)
我想我需要改变编码.我的初始xml文件似乎是ascii.有关如何使这项工作的任何想法?谢谢
我已经使用该xmltodict模块解析了一个xml文件,并将结果存储在词典的字典中。
现在我想删除的特殊字符@,并#在字典中的每一个关键。
def remove_using_json(parse_result):
data = {}
data = json.dumps(parse_result)
#print data
#for d in data:
for key, value in data.iterkeys():
if key[0] == '@':
data[key]=key.strip("@")
elif key[0] == '#':
data[key] =key.strip("#")
Run Code Online (Sandbox Code Playgroud) 我正在尝试使用库在 python 中将 xml 转换为 json xmltodict。虽然 xml 正在转换为 json,但在 dict 中的每个键之前,都会添加“@”前缀。以下是代码片段和示例输出:
import xmltodict
import json
with open('response.xml','r') as res_file:
doc = xmltodict.parse(res_file.read())
xml_json_str = json.dumps(doc)
final_json = json.loads(xml_json_str)
Run Code Online (Sandbox Code Playgroud)
输出:
"CustomerInfo": {
"@address": "Bangalore, Karnataka 560034",
"@email": "abc@gmail.com",
"@name": "Sam",
}
Run Code Online (Sandbox Code Playgroud)
如何一次性从所有密钥中删除@?
python ×11
xmltodict ×11
xml ×7
xml-parsing ×2
dictionary ×1
json ×1
list ×1
pipenv ×1
python-2.7 ×1
python-3.x ×1
xml-to-json ×1