2012-05-22 111 views
-1

解析xml我有一個非常奇怪和奇怪的XML(這不是我的錯),我想從它獲得一些信息與C#和LINQ。 XML是:使用xdocument解析xml與C#使用xdocument

<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,且點對於每個競爭者whic是「值」,但在一個週期我可以有更多點(「價值觀」)對於一個競爭對手,所以我必須以某種方式總結ti,我正在與這個一起努力,所以任何建議或幫助任何人?

+2

讀書給了我們更多的XML的,所以我們有一個更好的線索。 – Davio

+0

你是否缺少一些xml? – esskar

+0

有一個原因,有一個預覽 - 所以你可以看到你要發佈.. – t3hn00b

回答

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 

} 
+0

謝謝你,我已經使用你的代碼,只需稍作修改,它就可以工作! – GoranB