How can I turn an XML document into an easy to use C# object?

╄→尐↘猪︶ㄣ 提交于 2019-12-25 05:33:32

问题


The Distributed project "World Community Grid" has the ability to get detailed user information such as:

<?xml version="1.0" encoding="UTF-8"?>

<MemberStatsWithTeamHistory>
    <MemberStats>
   <MemberStat>
      <Name>makerofthings7</Name>
      <MemberId>876300</MemberId>
      <TeamId>0QGNJ4D832</TeamId>
      <RegisterDate>2013-12-08</RegisterDate>
      <LastResult>2013-12-11T11:58:51</LastResult>
      <NumDevices>4</NumDevices>
      <StatisticsTotals>
         <RunTime>1290126</RunTime>
         <RunTimeRank>415174</RunTimeRank>
         <Points>61710</Points>
         <PointsRank>293387</PointsRank>
         <Results>175</Results>
         <ResultsRank>282858</ResultsRank>
      </StatisticsTotals>
      <StatisticsAverages>
         <RunTimePerDay>322532</RunTimePerDay>
         <RunTimePerResult>7372</RunTimePerResult>
         <PointsPerHourRunTime>172.19713423320002</PointsPerHourRunTime>
         <PointsPerDay>15427.5</PointsPerDay>
         <PointsPerResult>352.62857142857104</PointsPerResult>
         <ResultsPerDay>43.75</ResultsPerDay>
      </StatisticsAverages>
      <Resource>
         <Url>http://www.worldcommunitygrid.org/stat/viewMemberInfo.do?userName=makerofthings7&amp;xml=true</Url>
         <Description>makerofthings7</Description>
      </Resource>
   </MemberStat>
</MemberStats>
    <TeamHistory>
   <Team>
      <Name>Ripple Labs</Name>
      <TeamId>0QGNJ4D832                          </TeamId>
      <JoinDate>2013-12-08</JoinDate>
      <StatisticsTotals>
         <RunTime>688331</RunTime>
         <Points>33548</Points>
         <Results>99</Results>
      </StatisticsTotals>
   </Team>
    </TeamHistory>
   <MemberStatsByProjects>
      <Project>         <ProjectName>Mapping Cancer Markers</ProjectName>
         <ProjectShortName>mcm1</ProjectShortName>
         <RunTime>518163</RunTime>
         <Points>22918</Points>
         <Results>39</Results>
      </Project>      <Project>         <ProjectName>The Clean Energy Project - Phase 2</ProjectName>
         <ProjectShortName>cep2</ProjectShortName>
         <RunTime>61555</RunTime>
         <Points>3422</Points>
         <Results>4</Results>
      </Project>      <Project>         <ProjectName>FightAIDS@Home</ProjectName>
         <ProjectShortName>faah</ProjectShortName>
         <RunTime>710408</RunTime>
         <Points>35370</Points>
         <Results>132</Results>
      </Project>   </MemberStatsByProjects>
</MemberStatsWithTeamHistory>

I was able to get this XML by going here:

 http://www.worldcommunitygrid.org/verifyMember.do?name=makerofthings7&code=SECRET CODE HERE

Then extracting the secret code from this page which is unique on a per person basis.

Since this is such a good cause, I want to encourage other people to use this API and "compete" for a cure.

Question

How can I take this XML file and convert it into a C# class that can easily be used by consuming users?


回答1:


You can use XmlSerialzier....

XmlSerializer serializer = new XmlSerializer(typeof(MemberStatsWithTeamHistory));
var obj = serializer.Deserialize(File.OpenRead(fname)) as MemberStatsWithTeamHistory;

PS: It is not the same as @AydinAdn's answer. I changed, for example, MemberStatsByProjects definition to make it work


public class StatisticsTotals
{
    public string RunTime { get; set; }
    public string RunTimeRank { get; set; }
    public string Points { get; set; }
    public string PointsRank { get; set; }
    public string Results { get; set; }
    public string ResultsRank { get; set; }
}

public class StatisticsAverages
{
    public string RunTimePerDay { get; set; }
    public string RunTimePerResult { get; set; }
    public string PointsPerHourRunTime { get; set; }
    public string PointsPerDay { get; set; }
    public string PointsPerResult { get; set; }
    public string ResultsPerDay { get; set; }
}

public class Resource
{
    public string Url { get; set; }
    public string Description { get; set; }
}

public class MemberStat
{
    public string Name { get; set; }
    public string MemberId { get; set; }
    public string TeamId { get; set; }
    public string RegisterDate { get; set; }
    public string LastResult { get; set; }
    public string NumDevices { get; set; }
    public StatisticsTotals StatisticsTotals { get; set; }
    public StatisticsAverages StatisticsAverages { get; set; }
    public Resource Resource { get; set; }
}

public class MemberStats
{
    public MemberStat MemberStat { get; set; }
}

public class StatisticsTotals2
{
    public string RunTime { get; set; }
    public string Points { get; set; }
    public string Results { get; set; }
}

public class Team
{
    public string Name { get; set; }
    public string TeamId { get; set; }
    public string JoinDate { get; set; }
    public StatisticsTotals2 StatisticsTotals { get; set; }
}

public class TeamHistory
{
    public Team Team { get; set; }
}

public class Project
{
    public string ProjectName { get; set; }
    public string ProjectShortName { get; set; }
    public string RunTime { get; set; }
    public string Points { get; set; }
    public string Results { get; set; }
}

public class MemberStatsWithTeamHistory
{
    public MemberStats MemberStats { get; set; }
    public TeamHistory TeamHistory { get; set; }
    public List<Project> MemberStatsByProjects { get; set; }
}



回答2:


I converted it from xml to json http://www.utilities-online.info/xmltojson/#.Uqi40eIa6So
And from json to csharp: http://json2csharp.com/
Hope that helps :)

public class StatisticsTotals
{
    public string RunTime { get; set; }
    public string RunTimeRank { get; set; }
    public string Points { get; set; }
    public string PointsRank { get; set; }
    public string Results { get; set; }
    public string ResultsRank { get; set; }
}

public class StatisticsAverages
{
    public string RunTimePerDay { get; set; }
    public string RunTimePerResult { get; set; }
    public string PointsPerHourRunTime { get; set; }
    public string PointsPerDay { get; set; }
    public string PointsPerResult { get; set; }
    public string ResultsPerDay { get; set; }
}

public class Resource
{
    public string Url { get; set; }
    public string Description { get; set; }
}

public class MemberStat
{
    public string Name { get; set; }
    public string MemberId { get; set; }
    public string TeamId { get; set; }
    public string RegisterDate { get; set; }
    public string LastResult { get; set; }
    public string NumDevices { get; set; }
    public StatisticsTotals StatisticsTotals { get; set; }
    public StatisticsAverages StatisticsAverages { get; set; }
    public Resource Resource { get; set; }
}

public class MemberStats
{
    public MemberStat MemberStat { get; set; }
}

public class StatisticsTotals2
{
    public string RunTime { get; set; }
    public string Points { get; set; }
    public string Results { get; set; }
}

public class Team
{
    public string Name { get; set; }
    public string TeamId { get; set; }
    public string JoinDate { get; set; }
    public StatisticsTotals2 StatisticsTotals { get; set; }
}

public class TeamHistory
{
    public Team Team { get; set; }
}

public class Project
{
    public string ProjectName { get; set; }
    public string ProjectShortName { get; set; }
    public string RunTime { get; set; }
    public string Points { get; set; }
    public string Results { get; set; }
}

public class MemberStatsByProjects
{
    public List<Project> Project { get; set; }
}

public class MemberStatsWithTeamHistory
{
    public MemberStats MemberStats { get; set; }
    public TeamHistory TeamHistory { get; set; }
    public MemberStatsByProjects MemberStatsByProjects { get; set; }
}

public class RootObject
{
    public MemberStatsWithTeamHistory MemberStatsWithTeamHistory { get; set; }
}



回答3:


First I use xsd.exe to create the classes from the xml using an schema XSD. (xsd.exe). This will create a class. Then use Generics:

public class XmlSerializer<T>
    {
        /// <summary>
        /// Load a Xml File and Deserialize into and object         
        /// </summary>
        /// <param name="xml">Xml String</param>
        /// <returns>Object representing the xml. You should catch an InvalidCastException</returns>
        public T DeserializeXmlProductContent(String xml)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));

            T obj;
            using (StringReader reader = new StringReader(xml))
            {
                obj = (T)serializer.Deserialize(reader);
            }
            return obj;


        }
        /// <summary>
        /// Serialize an Object to a Xml String
        /// </summary>
        /// <param name="obj">Any Object</param>
        /// <returns>Xml String</returns>
        public String SerializeProductContentToXml(T obj)
        {

            XmlSerializer serializer = new XmlSerializer(obj.GetType());

            using (StringWriter writer = new StringWriter())
            {
                serializer.Serialize(writer, obj);

                return writer.ToString();
            }

        }
    }



回答4:


copy the XML to clipboard, go to a C# class file, place your cursor where you want the classes to be pasted and then go to Edit->Paste Special->Paste XML as C# class and you're done.



来源:https://stackoverflow.com/questions/20527872/how-can-i-turn-an-xml-document-into-an-easy-to-use-c-sharp-object

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