1

尝试创建一个 python 脚本来显示来自每 5-7 秒更改一次的复杂 XML 文件的数据。下面是我正在使用的示例 XML 文件...

<bsgame source="TAS Baseball/Softball" version="5.17.00" 
generated="4/9/2019">
<venue gameid="SB0409-1"
       visid="IUP-S" homeid="JOHN" visname="Indiana (PA)" 
homename="Seton Hill"
       date="4/9/2019" location="Greensburg, PA" 
stadium="" duration="" attend="0"
       leaguegame="N" start="3:00 PM" dhgame="1" 
schedinn="7"
       weather="sunny and warm">
<umpires></umpires>
<notes>
  <note text="Weather: sunny and warm"></note>
  <note text="Game: livegame"></note>
</notes>
<rules batters="9,9" usedh="Y"></rules>
</venue>
<team vh="V" id="IUP-S" name="Indiana (PA)" code="IUP-S">
<linescore line="0,0,0,0,1,1,3" runs="5" hits="9" 
 errs="2" lob="7">
  <lineinn inn="1" score="0"></lineinn>
  <lineinn inn="2" score="0"></lineinn>
  <lineinn inn="3" score="0"></lineinn>
  <lineinn inn="4" score="0"></lineinn>
  <lineinn inn="5" score="1"></lineinn>
  <lineinn inn="6" score="1"></lineinn>
  <lineinn inn="7" score="3"></lineinn>
</linescore>
<team vh="H" id="SHU-S" name="Seton Hill" code="SHU-S">
<linescore line="0,0,0,0,0,1,X" runs="1" hits="4" 
  errs="2" lob="3">
  <lineinn inn="1" score="0"></lineinn>
  <lineinn inn="2" score="0"></lineinn>
  <lineinn inn="3" score="0"></lineinn>
  <lineinn inn="4" score="0"></lineinn>
  <lineinn inn="5" score="0"></lineinn>
  <lineinn inn="6" score="1"></lineinn>
  <lineinn inn="7" score=""></lineinn>
</linescore>

我注意到诸如 StretchInternet 之类的服务将这样的 XML 转换为 Json 以显示数据。我已经想出了如何在 Python 中使用 xmltodict 将 XML 转换为 Json。

 import json
 import xmltodict

 with open("/Volumes/GoogleDrive/My Drive/LIVE/XMLs/SB_Demo.xml", 'r') as f:
     xmlString = f.read()

 jsonString = json.dumps(xmltodict.parse(xmlString), indent=4)

 print("\nJSON output(output.json):")
 print(jsonString)

 with open("output.json", 'w') as f:
     f.write(jsonString)

我很困惑从这里去哪里。最终,我希望能够在视频广播中显示两个“团队”的总 RUNS (@runs)。但是,我是一个循序渐进的人。第 1 步...如何使用 xmltodict 解析此 XML 并仅显示两个“团队”的 @runs?

4

1 回答 1

0

对于初学者,您应该与您的报价用法保持一致(使用“或')

此外,您的 xml 在每个之后都缺少</team>结束标记<linescore>

至于您的问题 - 您正在将您的 xml dict 转换为 JSON 字符串json.dumps,这对您正在尝试的内容没有用处。将您的 xmltodict 对象作为 Python dict 访问

with open("YOUR_XML_FILE.xml", 'r') as f:
    xmlString = f.read()

xmlDict = xmltodict.parse(xmlString)

for team in xmlDict['bsgame']['team']:
    print(team['@name'], 'Runs :')
    print(team['linescore']['@runs'])

这导致

Indiana (PA) Runs :
5
Seton Hill Runs :
1
于 2019-05-13T05:00:19.477 回答