Search code examples
linqsyntaxxelement

Linq Query syntax System.Xml.Linq.XElement


I am querying an Xelement and attempting to get string values into another object

Here is the Xml

<Test ID="2278388" TestCompleted="2013-06-25T14:13:07.137">
<TestResult>P</TestResult> 
<TestType>
 <Name>Nursing</Name> 
 <Part1>ULE</Part1> 
 <Part2>PRI</Part2> 
</TestType>
<ExamCode>P1</ExamCode>
</Test>

using webclient i have manged to get this into an Xelement 'Elm' I have worked out how to get the Name part1 and part2 but cant figure out how to get ID ,Testresult, Completed, or Exam Code

private BssClient XMLtoBssClient()
        {
            BssClient BssC = new BssClient();


            BssC.caseType = ((wch.Elm).Descendants("TestType").Select(x => x.Element("Name").Value).FirstOrDefault()) ?? "";
            BssC.matter1 = ((wch.Elm).Descendants("TestType").Select(x => x.Element("Part1").Value).FirstOrDefault()) ?? "";
            BssC.matter2 = ((wch.Elm).Descendants("TestType").Select(x => x.Element("Part2").Value).FirstOrDefault()) ?? "";
            BssC.ExamCode = 
            BssC.ID =
            BssC.DateCompleted =

            return BssC;

    } 

i have googled and looked on MSDN and tried various things but this really new to me Any help much appreciated


Solution

  • The following code should work:

    private BssClient XMLtoBssClient()
        {
            BssClient BssC = new BssClient();
    
    
            BssC.caseType = ((wch.Elm).Descendants("TestType").Select(x => x.Element("Name").Value).FirstOrDefault()) ?? "";
            BssC.matter1 = ((wch.Elm).Descendants("TestType").Select(x => x.Element("Part1").Value).FirstOrDefault()) ?? "";
            BssC.matter2 = ((wch.Elm).Descendants("TestType").Select(x => x.Element("Part2").Value).FirstOrDefault()) ?? "";
            BssC.ExamCode = ((wch.Elm).Elements("ExamCode").Select(x => x.Value).FirstOrDefault()) ?? "";
            BssC.TestResult = ((wch.Elm).Elements("TestResult").Select(x => x.Value).FirstOrDefault()) ?? "";
            BssC.ID = ((wch.Elm).Attributes("ID").Select(x => x.Value).FirstOrDefault()) ?? "";
            BssC.DateCompleted = ((wch.Elm).Attributes("TestCompleted").Select(x => x.Value).FirstOrDefault()) ?? "";
    
    
            return BssC;
    
    } 
    

    However I reccommend you look into Xml serialization as it will make this an awful lot easier to maintain and a lot simpler.