我想從XML文件中創建一個括號樹。從C#中的XML文件創建一個括號樹
在托架的匹配由四個小組。該團隊的獲勝者前進到下一輪。
如果比賽包括3支球隊和一個孩子的比賽,那麼孩子匹配決定第四小組父比賽。
這裏是我的XML文件:
<?xml version="1.0" encoding="utf-8" ?>
<Round>
<Match>
<Team id="A1">Apples</Team>
<Team id="B2">Banannas</Team>
<Team id="C3">Cantalopes</Team>
<Team id="D4">Durians</Team>
</Match>
<Match>
<Team id="A2">Avocados</Team>
<Team id="B2">Blueberry</Team>
<Team id="C3">Coconut</Team>
<Team id="TBD">
<Match>
<Team id="A3">Apricots</Team>
<Team id="B5">Banannas</Team>
<Team id="C9">Cantalopes</Team>
<Team id="D6">Durians</Team>
</Match>
</Team>
</Match>
</Round>
這裏是我的函數來創建樹:
private void CreateTree(XmlTextReader reader, Node<Match<Team>> parent, Match<Team> currentMatch)
{
if (reader.Read())
{
if (reader.IsStartElement())
{
switch (reader.Name)
{
case "Match": //We need to make a new match!
currentMatch = new Match<Team>();
Node<Match<Team>> child = new Node<Match<Team>>(currentMatch);
parent.Add(currentMatch);
CreateTree(reader, child, currentMatch);
break;
case "Team": //We need to add a team!
string id = reader.GetAttribute("id");
if (id != "TBD")
{
string name = reader.Value;
currentMatch.Add(new Team(id, name));
}
else
{
currentMatch.Add(Team.Tbd);
}
CreateTree(reader, parent, currentMatch);
break;
default:
break;
}
}
else
{
CreateTree(reader, parent.Parent, null);
}
}
}
我最初調用該函數以下列方式:
string path = Path.Combine(Environment.CurrentDirectory, @"Data\", fileName);
XmlTextReader reader = new XmlTextReader(path);
CreateTree(reader, tree, null);
reader.Close();
不幸的是,這不起作用,我的樹是空的,而且我很難弄清楚我做錯了什麼。任何幫助搞清楚這將不勝感激!
謝謝!
XML本身是一棵樹。所以'XElement.Load'會給你一棵樹。 –