我正在查询Xelement并尝试将字符串值转换为另一个对象
这是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>
使用webclient我已经将其变成了一个Xelement'Elm' 我已经弄清楚如何获得Name part1和part2 但无法弄清楚如何获得ID,Testresult,已完成或考试代码
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;
}
我用Google搜索并查看MSDN并尝试了各种各样的事情 但这对我来说真的很新 任何帮助非常感谢
答案 0 :(得分:1)
以下代码应该有效:
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;
}
但是我建议你研究一下Xml serialization,因为它会使维护更容易,更简单。