xml parsing - code refactoring issue

浪子不回头ぞ 提交于 2019-12-02 13:15:19

Given your XML is tiny, you probably don't have to worry too much about performance. You can just do the whole thing in one go, making use of the built in explicit conversions:

var data = new OutputData
{
    FirstOne = (string) doc.Descendants("FirstOne").Single(),
    SecondOne = (string) doc.Descendants("SecondOne").Single(),
    IsMale = (bool) doc.Descendants("IsMale").Single(),
    MarkOne = (double) doc.Descendants("MarkOne").Single(),
    MarkTwo = (double) doc.Descendants("MarkTwo").Single(),
    Slope = (double) doc.Descendants("Slope").Single()
};

As an aside, Descendants will never return anything implementing IList<XElement>, so you can definitely remove that.

Try XML Linq

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);
            var root = doc.Elements("RootData").Select(x => new
            {
                passResults = x.Elements("PassResult").Select(y => new
                {
                    firstOne = (string)y.Element("FirstOne"),
                    secondOne = (string)y.Element("SecondOne"),
                    isMale = (Boolean)y.Element("IsMale")
                }).FirstOrDefault(),
                testResult = x.Elements("TestResult").Select(y => new {
                    markOne = (int)y.Element("MarkOne"),
                    markTwo = (int)y.Element("MarkTwo"),
                    slope = (int)y.Element("Slope")
                }).FirstOrDefault(),
                toneTestResult = x.Elements("ToneTestResult").Select(y => new {
                    totalTime = (int)y.Element("TotalTime"),
                    correctPecentage = (int)y.Element("CorrectPercentage")
                }).FirstOrDefault(),
                questionnaireResult = x.Elements("QuestionnaireResult").Elements("Question").Select(y => new {
                    question = (int)y.Attribute("Id"),
                    answer = (string)y.Descendants("Answer").FirstOrDefault().Attribute("Id")
                }).ToList(),
            }).FirstOrDefault();

        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!