读取xml文件的多个子节点

Pet*_*r C 13 c# xml visual-studio-2010

我创建了一个带有示例内容的Xml文件,如下所示:

<?xml version="1.0" encoding="utf-8" ?>
<Periods>
  <PeriodGroup name="HER">
    <Period>
      <PeriodName>Prehistoric</PeriodName>
      <StartDate>-500000</StartDate>
      <EndDate>43</EndDate>
    </Period>
    <Period>
      <PeriodName>Iron Age</PeriodName>
      <StartDate>-800</StartDate>
      <EndDate>43</EndDate>
    </Period>
    <Period>
      <PeriodName>Roman</PeriodName>
      <StartDate>43</StartDate>
      <EndDate>410</EndDate>
    </Period>
  </PeriodGroup>
  <PeriodGroup name="CAFG">
    <Period>
      <PeriodName>Prehistoric</PeriodName>
      <StartDate>-500000</StartDate>
      <EndDate>43</EndDate>
    </Period>
    <Period>
      <PeriodName>Roman</PeriodName>
      <StartDate>43</StartDate>
      <EndDate>410</EndDate>
    </Period>
    <Period>
      <PeriodName>Anglo-Saxon</PeriodName>
      <StartDate>410</StartDate>
      <EndDate>800</EndDate>
    </Period>   
  </PeriodGroup>
</Periods>
Run Code Online (Sandbox Code Playgroud)

我需要能够读取所选PeriodGroup中的Period节点子节点.我想PeriodName可能是Period的一个属性,如果这更合理的话.

我看了很多例子,但似乎没有一点是正确的,似乎有几十种不同的方法,一些使用XmlReader,一些使用XmlTextReader,一些不使用.由于这是我第一次阅读Xml文件,我想我会问是否有人可以给我一个指针.我有一些工作只是为了尝试,但感觉很笨.我正在使用VS2010和c#.另外,我看到很多人都在使用LINQ-Xml,所以我很欣赏使用这种方法的优点和缺点.

string PG = "HER";
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("./Xml/XmlFile.xml"));
string text = string.Empty;
XmlNodeList xnl = doc.SelectNodes("/Periods/PeriodGroup");
foreach (XmlNode node in xnl)
{
    text = node.Attributes["name"].InnerText;
    if (text == PG)
    {
        XmlNodeList xnl2 = doc.SelectNodes("/Periods/PeriodGroup/Period");
        foreach (XmlNode node2 in xnl2)
        {
            text = text + "<br>" + node2["PeriodName"].InnerText;
            text = text + "<br>" + node2["StartDate"].InnerText;
            text = text + "<br>" + node2["EndDate"].InnerText;
        }
    }
    Response.Write(text);
}
Run Code Online (Sandbox Code Playgroud)

DGi*_*bbs 14

您可以像这样使用XPath方法:

XmlNodeList xnl = doc.SelectNodes(string.Format("/Periods/PeriodGroup[@name='{0}']/Period", PG));
Run Code Online (Sandbox Code Playgroud)

虽然它更喜欢LINQ to XML,但它的可读性.

这将Period根据提供的PeriodGroup name属性返回节点子节点,例如HER:

XDocument xml = XDocument.Load(HttpContext.Current.Server.MapPath(FileLoc));

var nodes = (from n in xml.Descendants("Periods")
            where n.Element("PeriodGroup").Attribute("name").Value == "HER"
            select n.Element("PeriodGroup").Descendants().Elements()).ToList();
Run Code Online (Sandbox Code Playgroud)

结果:

<PeriodName>Prehistoric</PeriodName>
<StartDate>-500000</StartDate>
<EndDate>43</EndDate>

<PeriodName>Iron Age</PeriodName>
<StartDate>-800</StartDate>
<EndDate>43</EndDate>

<PeriodName>Roman</PeriodName>
<StartDate>43</StartDate>
<EndDate>410</EndDate>
Run Code Online (Sandbox Code Playgroud)

查询非常简单

from n in xml.Descendants("Periods")
Run Code Online (Sandbox Code Playgroud)

将返回元素的后代元素的集合Periods.然后where,我们使用基于属性值过滤此节点集合:

where n.Element("PeriodGroup").Attribute("name").Value == "HER"
Run Code Online (Sandbox Code Playgroud)

然后将集合过滤到PeriodGroup具有name值为的属性的元素HER

最后,我们选择PeriodGroup元素并获取它的后代节点

select n.Element("PeriodGroup").Descendants().Elements()
Run Code Online (Sandbox Code Playgroud)

编辑(见评论)

由于此表达式的结果只是一个查询,因此我们使用.ToList()枚举集合并返回包含所需值的对象.您还可以创建匿名类型来存储元素值,例如:

var nodes = (from n in xml.Descendants("Period").
             Where(r => r.Parent.Attribute("name").Value == "HER")
             select new
             {
                  PeriodName = (string)n.Element("PeriodName").Value,
                  StartDate = (string)n.Element("StartDate").Value,
                  EndDate = (string)n.Element("EndDate").Value
             }).ToList();

//Crude demonstration of how you can reference each specific element in the result
//I would recommend using a stringbuilder here..
foreach (var n in nodes)
{
      text += "<br>" + n.PeriodName;
      text += "<br>" + n.StartDate;
      text += "<br>" + n.EndDate;
}
Run Code Online (Sandbox Code Playgroud)

这是nodes查询运行后对象的样子:

在此输入图像描述


sha*_*rov 5

由于该XmlDocument.SelectNodes方法实际上接受 XPath 表达式,因此您可以随意执行以下操作:

XmlNodeList xnl = doc.SelectNodes("/Periods/PeriodGroup[@name='" + PG + "']/Period");
foreach (XmlNode node in xnl) {
    // Every node here is a <Period> child of the relevant <PeriodGroup>.
}
Run Code Online (Sandbox Code Playgroud)

您可以在w3schools了解有关 XPath 的更多信息。