使用xdocument使用C#解析xml

时间:2012-05-22 10:46:31

标签: c# xml linq-to-xml

我有一个非常奇怪和奇怪的xml(这不是我的错),我想用c#和linq从中获取一些信息。 XML是:

<Match BeginTime="2012-05-16T13:21:56.6737546+02:00" EndTime="2012-05-16T13:24:04.3994176+02:00" Winner="2">

  <Period Number="1" MaximumDuration="PT2M" BeginTime="2012-05-16T13:21:56.6737546+02:00" 
    EndTime="2012-05-16T13:22:25.3952338+02:00" MatchDuration="PT2M" Winner="2">
    <Point Competitor="1" Value="1" MatchTime="PT6.5178048S" Time="2012-05-16T13:22:03.6018269+02:00" />
    <Point Competitor="2" Value="2" MatchTime="PT1M57S" Time="2012-05-16T13:22:21.4017106+02:00" />
  </Period>

  <Pause MaximumDuration="PT30S" AutomaticallyStartTime="true" BeginTime="2012-05-16T13:22:25.3952338+02:00" 
    EndTime="2012-05-16T13:22:36.1092608+02:00" />
  <Period Number="2" MaximumDuration="PT2M" BeginTime="2012-05-16T13:22:37.2592378+02:00"
     EndTime="2012-05-16T13:23:33.0777937+02:00" MatchDuration="PT2M" Winner="2">
    <Point Competitor="2" Value="3" MatchTime="PT10.2121084S" Time="2012-05-16T13:22:47.4932385+02:00" />
    <Point Competitor="1" Value="2" MatchTime="PT15.2950443S" Time="2012-05-16T13:22:52.5951376+02:00" />
    <Point Competitor="2" Value="2" MatchTime="PT41.1295728S" Time="2012-05-16T13:23:18.3988393+02:00" />
  </Period>
  <Pause MaximumDuration="PT30S" AutomaticallyStartTime="true" BeginTime="2012-05-16T13:23:33.0777937+02:00" />
  <Period Number="3" MaximumDuration="PT2M" />
</Match>  

你可以看到我有3个时期,在每个时期我都有1或2的竞争者号码,并且每个竞争者的点数都是“价值”,但在一个时期我可以有更多的积分(“价值”)对于一个竞争对手,所以我必须以某种方式总结,我正在与这一个,所以任何建议或帮助任何人?

1 个答案:

答案 0 :(得分:1)

示例XML

  <root>
      <ul class="connectedSortable ui-sortable" tid="1146">
        <li class="termName">Fall 2010</li>
        <li class="course" cid="2826" style="">FAC101: Art Appreciation</li>
        <li class="course" cid="2827" style="">CSC105: Using Modern Operating Systems</li>
        <li class="course" cid="2828" style="">CSC110: Introduction to Computer Science</li>
      </ul>
      <ul class="connectedSortable ui-sortable" tid="1156">
        <li class="termName">Winter 2011</li>
        <li class="course" cid="2829" style="">FAC105: Leadership and Problem Solving</li>
      </ul>
      <ul class="connectedSortable ui-sortable" tid="1159">
        <li class="termName">Spring 2011</li>
      </ul>
    </root>

用C#阅读

var reader = new StringReader(termsXml);
var xdoc = XDocument.Load(reader);

var terms = from term in xdoc.Descendants("ul")
            select new
            {
                TermId = term.Attribute("tid").Value,
                Courses = term.Descendants("li")
            };

foreach (var term in terms)
{
    var courseIds = (from course in term.Courses
                        where course.Attribute("cid") != null
                        select course.Attribute("cid").Value).ToList();

    // do stuff with the courseids here

}