假设我的 XML 树中有四个级别,其中级别 3 可以有相同的子两次,即在以下 XML 中:
<Game>
<Round>
<roundNumber>1</roundNumber>
<Door>
<doorName>abd11</doorName>
<Value>
<xVal1>0</xVal1>
<xVal2>25</xVal2>
<pVal>0.31</pVal>
</Value>
<Value>
<xVal1>25</xVal1>
<xVal2>50</xVal2>
<pVal>0.04</pVal>
</Value>
<Value>
<xVal1>50</xVal1>
<xVal2>75</xVal2>
<pVal>0.19</pVal>
</Value>
<Value>
<xVal1>75</xVal1>
<xVal2>100</xVal2>
<pVal>0.46</pVal>
</Value>
</Door>
<Door>
<doorName>vvv1133</doorName>
<Value>
<xVal1>60</xVal1>
<xVal2>62</xVal2>
<pVal>1.0</pVal>
</Value>
</Door>
</Round>
<Round>
<roundNumber>2</roundNumber>
<Door>
<doorName>eee</doorName>
<Value>
<xVal1>0</xVal1>
<xVal2>-25</xVal2>
<pVal>0.31</pVal>
</Value>
<Value>
<xVal1>-25</xVal1>
<xVal2>-50</xVal2>
<pVal>0.04</pVal>
</Value>
<Value>
<xVal1>-50</xVal1>
<xVal2>-75</xVal2>
<pVal>0.19</pVal>
</Value>
<Value>
<xVal1>-75</xVal1>
<xVal2>-100</xVal2>
<pVal>0.46</pVal>
</Value>
</Door>
<Door>
<doorName>cc</doorName>
<Value>
<xVal1>-60</xVal1>
<xVal2>-62</xVal2>
<pVal>0.3</pVal>
</Value>
<Value>
<xVal1>-70</xVal1>
<xVal2>-78</xVal2>
<pVal>0.7</pVal>
</Value>
</Door>
</Round>
</Game>
我Doors
每个都有两个Round
,那么问题是,使用Dom
or Sax
(或 Jdom 如果有帮助)可以
我在我的树上迭代并获取每个级别的数据?
此刻我“下降”了一个级别并获得了回合,这里:
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse (new File("input.xml"));
// normalize text representation
doc.getDocumentElement ().normalize ();
System.out.println ("Root element of the doc is " + // would produce Game
doc.getDocumentElement().getNodeName());
NodeList roundNodes = doc.getElementsByTagName("Round"); // roundNodes are the Rounds
int totalNodes = roundNodes.getLength(); // 2 by the example
System.out.println("Total number of Rounds are : " + totalNodes);
for (int i = 0; i < roundNodes.getLength() ; i++)
{
Node node = roundNodes.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE)
{
Element element = (Element)node;
NodeList firstDoorList = element.getElementsByTagName("Door");
Element firstDoorElement = (Element)firstDoorList.item(0);
NodeList textFNList = firstDoorElement.getChildNodes();
System.out.println("First Door : " + ((Node)textFNList.item(0)).getNodeValue().trim());
}
}
但似乎有很多迭代代码。
有没有一种简单的方法来提取该 XML 的数据?假设我每轮有 2 个 Doors 和一些 Rounds 数。
谢谢