0

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

Sonny123
  • 107
  • 1
  • 3
  • 12

1 Answers1

1

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.

Dave Williams
  • 2,166
  • 19
  • 25
  • Thanks very much Dave, much obliged to you, It was the Select(x => x.Value) that was throwing me – Sonny123 Jun 27 '13 at 12:50
  • Yeah, actually like I said this is a bit of a bodge way to do it. It works but I highly recommend you find an alternative e.g serialization because if you ever update or expand your xml this will be a nightmare to maintain. – Dave Williams Jun 27 '13 at 12:53