[英]How can I select only some child nodes from an XML file in C#?
I have an XML file that I want to parse. 我有一个要解析的XML文件。 It is longer than what I shall post here, but only this part interests me in this question:
它比我将在此处发布的内容更长,但是只有这一部分使我对这个问题感兴趣:
<Team>
<TeamId>1187457</TeamId>
<TeamName>Zanardi Redwings</TeamName>
<Arena>
<ArenaId>1184019</ArenaId>
<ArenaName>Evolution</ArenaName>
</Arena>
<League>
<LeagueId>37</LeagueId>
<LeagueName>România</LeagueName>
</League>
<Country>
<CountryId>36</CountryId>
<CountryName>România</CountryName>
</Country>
<LeagueLevelUnit>
<LeagueLevelUnitId>4109</LeagueLevelUnitId>
<LeagueLevelUnitName>V.171</LeagueLevelUnitName>
</LeagueLevelUnit>
<Region>
<RegionId>799</RegionId>
<RegionName>Prahova</RegionName>
</Region>
<YouthTeam>
<YouthTeamId>2337461</YouthTeamId>
<YouthTeamName>Little Redwings</YouthTeamName>
<YouthLeague>
<YouthLeagueId>436902</YouthLeagueId>
<YouthLeagueName>Normandie Ligue des jeunes</YouthLeagueName>
</YouthLeague>
</YouthTeam>
</Team>
From the part above, I only need to read the data from the TeamId
and TeamName
child nodes. 从上面的部分,我只需要从
TeamId
和TeamName
子节点读取数据。 To achieve this, I wrote the following code: 为此,我编写了以下代码:
Nodes = Node.SelectNodes("Team");
foreach (XmlNode j in Nodes)
{
XmlNodeList TeamDetails = j.SelectNodes("*");
foreach (XmlNode k in TeamDetails)
{
switch (k.Name)
{
case "TeamName":
{
UserTeamNames[counter] = k.InnerXml;
break;
}
case "TeamId":
{
if (!int.TryParse(k.InnerXml, out UserTeamIDs[counter]))
{
ShowErrorMessageBox("Parsing TeamID from XML file failed!"); //A function which sets some parameters for MessageBox.Show() then calls it
}
break;
}
}
}
}
In the code above, counter
is an int
variable, which I need in other part of the code. 在上面的代码中,
counter
是一个int
变量,我在代码的其他部分中需要它。
The code works perfectly, but I want to eliminate the useless looping and testing when the node I am working on is not either TeamName
or TeamID
. 该代码可以正常工作,但是当我正在处理的节点不是
TeamName
或TeamID
时,我想消除无用的循环和测试。
I suspect the answer I am looking for has something to do with XPath expressions, but I am not sure. 我怀疑我正在寻找的答案与XPath表达式有关,但我不确定。
How can I read the data from only the mentioned nodes, without any useless operations? 如何仅从提到的节点读取数据,而没有任何无用的操作?
You can use XmlDocument.GetElementsByTagName method. 您可以使用XmlDocument.GetElementsByTagName方法。 For your example I will do something like this :
对于您的示例,我将执行以下操作:
XmlNodeList elemList = doc.GetElementsByTagName("TeamName");
XmlNodeList elemList = doc.GetElementsByTagName("TeamId");
The result is An XmlNodeList containing a list of all matching nodes. 结果是一个XmlNodeList,其中包含所有匹配节点的列表。 If no nodes match name, the returned collection will be empty.
如果没有节点与名称匹配,则返回的集合将为空。
严格按照xpath而言,以下表达式应选择您的节点:
/Team/*[self::TeamId or self::TeamName]
You can filter the xml document using linq then work with your filtered data. 您可以使用linq过滤xml文档,然后使用过滤后的数据。
using System;
using System.Linq;
using System.Xml.Linq;
using System.IO;
using System.Xml;
static void Main(string[] args)
{
var document = new XDocument();
// use path to your xml file
using (FileStream fs = File.OpenRead("examp.xml"))
{
using (XmlTextReader reader = new XmlTextReader(fs))
{
document = XDocument.Load(reader);
}
}
int value;
var query = (from element in document.Element("Base").Elements("Team")
where int.TryParse(element.Element("TeamId").Value.ToString(), out value)
select new
{
TeamName = element.Element("TeamName").Value,
TeamId = element.Element("TeamId").Value
}).ToList();
// do further processing with filtered data
foreach (var item in query)
{
Console.WriteLine($"{item.TeamName}: {item.TeamId}");
}
Console.ReadKey();
}
Here is another option using LINQ to XML.First create your own class that will hold that data you are looking for like this: 这是另一个使用LINQ to XML的选项。首先创建自己的类,该类将保存您正在寻找的数据,如下所示:
public class TeamInfo
{
public string TeamName { get; set; }
public int TeamId { get; set; }
}
Then you would parse the xml into a list of objects like this: 然后,您将xml解析为这样的对象列表:
var data =
"<Team><TeamId>1187457</TeamId><TeamName>Zanardi Redwings</TeamName><Arena><ArenaId>1184019</ArenaId><ArenaName>Evolution</ArenaName></Arena><League><LeagueId>37</LeagueId><LeagueName>România</LeagueName></League><Country><CountryId>36</CountryId><CountryName>România</CountryName></Country><LeagueLevelUnit><LeagueLevelUnitId>4109</LeagueLevelUnitId><LeagueLevelUnitName>V.171</LeagueLevelUnitName></LeagueLevelUnit><Region><RegionId>799</RegionId><RegionName>Prahova</RegionName></Region><YouthTeam><YouthTeamId>2337461</YouthTeamId><YouthTeamName>Little Redwings</YouthTeamName><YouthLeague><YouthLeagueId>436902</YouthLeagueId><YouthLeagueName>Normandie Ligue des jeunes</YouthLeagueName></YouthLeague></YouthTeam></Team>";
var elm = new XElement("Base",data);
var decoded = System.Web.HttpUtility.HtmlDecode(elm.ToString());//this is to remove any formatting issues when we call .ToString()
var doc = XDocument.Parse(decoded);
var result = doc.Root.Descendants("Team")
.Select(y => new TeamInfo
{
TeamId = Convert.ToInt32(y.Element("TeamId").Value),
TeamName = y.Element("TeamName").Value
}).ToList();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.