使用嵌套标记解析XML属性的简单方法

时间:2016-07-24 21:04:58

标签: java xml dom

我目前正在尝试使用棒球比分解析XML文件。该文件将所有信息存储在属性中,这给我带来了一些麻烦。以下是设置示例。

<game id="2016/07/20/atlmlb-cinmlb-1" venue="Great American Ball Park">
    <linescore>
         <inning away="1" home="0"/>
         <r away="3" home="6" diff="3"/>
         <h away="9" home="12"/>
    </linescore>
    <winning_pitcher id="543101" last="test" first="bob">
    <losing_pitcher id="449173" last="test" first="joe">
 </game>

到目前为止我所拥有的是:

NamedNodeMap ga= game.getAttributes();
Node stadium = ga.getNamedItem("venue");
String stad = stadium.getNodeValue();

NodeList linescore = game.getChildNodes();
NamedNodeMap ls = linescore.item(3).getAttributes();
....

如果所有内容都存储在游戏属性中,这样会很好,但由于很多内容都是嵌套的,因此必须为子属性创建节点列表变得很麻烦,然后重复一遍,特别是在我尝试的时候抓住20-30个统计数据。是否有一种更简单的方式来说,从<r>获得主场比分,获胜的投手名字和失去投手的名字。

2 个答案:

答案 0 :(得分:1)

XPath使XML访问变得不那么麻烦:

  

是否有更简单的说法,从<r>

获取主分数
/game/linescore/r/@home
  

获胜投手的名字

/game/winning_pitcher/@first
  

失去了投手的名字

/game/losing_pitcher/@first

将上述XPath与How to read XML using XPath in Java结合使用。

答案 1 :(得分:1)

您可以尝试使用Jackson扩展XML:https://github.com/FasterXML/jackson-dataformat-xml,它允许您将XML序列化/反序列化为POJO&#39>

相关问题