如何在c#中将xml响应转换为类对象?

时间:2017-06-07 09:35:39

标签: c# xml

您好我要转换为cml的xml响应作为c#.i中的类对象从sql端获取xml并调用一个实用程序并获取xml并转到类对象中的convert但是使用我的代码不在类中返回null。任何人都知道我的问题在哪里,请告诉我。

这是我的xml数据:

<Users>
      <User>
            <UserId>1</UserId>
            <Email>abc@gmail.com</Email>
            <UserName>abc</UserName>
            <ProfileImage>20160816105401206.jpeg</ProfileImage>
            <Name>abc</Name>

            <InterestId>8</InterestId>
            <FeedId>4608</FeedId>
            <Description>Test</Description>
            <Interest>Cricekt</Interest>    

            <InterestId>12</InterestId>
            <FeedId>4609</FeedId>
            <Description>Test 2</Description>
            <Interest>Read</Interest>    
      </User>
       <User>
            <UserId>2</UserId>
            <Email>xyz@gmail.com</Email>
            <UserName>xyz</UserName>
            <ProfileImage>20160816105401207.jpeg</ProfileImage>
            <Name>xyz</Name>

            <InterestId>8</InterestId>
            <FeedId>4610</FeedId>
            <Description>Test 3</Description>
            <Interest>swim</Interest>    

            <InterestId>12</InterestId>
            <FeedId>4610</FeedId>
            <Description>Test 3</Description>
            <Interest>drive</Interest>    
      </User>
 </Users>

这是我在c#中的课程:

        [XmlRoot]
    public class Users
    {
        [XmlRoot]
        public class User
        {
            [XmlElement]
            public int UserId { get; set; }

            [XmlElement]
            public string Email { get; set; }

            [XmlElement]
            public string UserName { get; set; }

            [XmlElement]
            public string ProfileImage { get; set; }

            [XmlElement]
            public string Name { get; set; }

            [XmlElement]
            public int FeedId { get; set; }

            [XmlElement]
            public string Description { get; set; }

            [XmlElement]
            public string Interest { get; set; }

            [XmlElement]
            public int InterestId { get; set; }              

        }

        [XmlArray("UserList")]
        [XmlArrayItem("User")]
        public User[] ListUsers { get; set; }
    }

这是我在c#中的方法:

    public string xmldata()
    {           
        Users obju = new Users();

            string xml = "";
            DataSet ds = DataAccess.ExecuteDataset(Settings.ConnectionString(), "Getxml",1,10);
            if (ds != null && ds.Tables.Count > 0)
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    xml += ds.Tables[0].Rows[i]["XML_F52E2B61-18A1-11d1-B105-00805F49916B"].ToString();
                }
            }

            var serializer = new XmlSerializer(typeof(Users));
            Users result;

            using (TextReader reader = new StringReader(xml))
            {
                result = (Users)serializer.Deserialize(reader);// here i am not getting xml to in class 
            }                                               
        return null;
    }

3 个答案:

答案 0 :(得分:1)

没有<UserList>包装它们,所以这不是一个xml数组。相反,使用:

[XmlElement("User")]
public User[] ListUsers { get; set; }

或更好:List<User>代替User[];我个人有:

[XmlElement("User")]
public List<User> Users {get; } = new List<User>();

(但这也要求您将根类型重命名为其他内容)

User上,它不是根,因此[XmlRoot]是多余的;并且[XmlElement]是默认设置并自动设置,因此您也可以从[XmlElement]删除所有User

要表明一切正常:

using System;
using System.IO;
using System.Xml.Serialization;

public class Users
{
    public class User
    {
        public int UserId { get; set; }
        public string Email { get; set; }
        public string UserName { get; set; }
        public string ProfileImage { get; set; }
        public string Name { get; set; }
        public int FeedId { get; set; }
        public string Description { get; set; }
        public string Interest { get; set; }
        public int InterestId { get; set; }
    }

    [XmlElement("User")]
    public User[] ListUsers { get; set; }
}
static class Program
{
    static void Main()
    {
        var ser = new XmlSerializer(typeof(Users));
        using (var sr = new StringReader(xml))
        {
            var obj = (Users)ser.Deserialize(sr);
            Console.WriteLine(obj.ListUsers.Length); // 2
        }
    }



    const string xml = @"<Users>
      <User>
            <UserId>1</UserId>
            <Email>abc@gmail.com</Email>
            <UserName>abc</UserName>
            <ProfileImage>20160816105401206.jpeg</ProfileImage>
            <Name>abc</Name>

            <InterestId>8</InterestId>
            <FeedId>4608</FeedId>
            <Description>Test</Description>
            <Interest>Cricekt</Interest>    

            <InterestId>12</InterestId>
            <FeedId>4609</FeedId>
            <Description>Test 2</Description>
            <Interest>Read</Interest>    
      </User>
       <User>
            <UserId>2</UserId>
            <Email>xyz@gmail.com</Email>
            <UserName>xyz</UserName>
            <ProfileImage>20160816105401207.jpeg</ProfileImage>
            <Name>xyz</Name>

            <InterestId>8</InterestId>
            <FeedId>4610</FeedId>
            <Description>Test 3</Description>
            <Interest>swim</Interest>    

            <InterestId>12</InterestId>
            <FeedId>4610</FeedId>
            <Description>Test 3</Description>
            <Interest>drive</Interest>    
      </User>
 </Users>";

}

答案 1 :(得分:1)

将此类用于序列化和不稳定

[XmlRoot(ElementName="User")]
    public class User {
        [XmlElement(ElementName="UserId")]
        public string UserId { get; set; }
        [XmlElement(ElementName="Email")]
        public string Email { get; set; }
        [XmlElement(ElementName="UserName")]
        public string UserName { get; set; }
        [XmlElement(ElementName="ProfileImage")]
        public string ProfileImage { get; set; }
        [XmlElement(ElementName="Name")]
        public string Name { get; set; }
        [XmlElement(ElementName="InterestId")]
        public List<string> InterestId { get; set; }
        [XmlElement(ElementName="FeedId")]
        public List<string> FeedId { get; set; }
        [XmlElement(ElementName="Description")]
        public List<string> Description { get; set; }
        [XmlElement(ElementName="Interest")]
        public List<string> Interest { get; set; }
    }

    [XmlRoot(ElementName="Users")]
    public class Users {
        [XmlElement(ElementName="User")]
        public List<User> User { get; set; }
    }

答案 2 :(得分:1)

这里似乎有2种完全不同的xml结构;一个整齐地列在问题中,一个逐条列出 - 在评论中。非商品化,我的意思是每个对象都没有包装,每个元素都会流入,如下所示:

<InterestId>8</InterestId>
<FeedId>4608</FeedId>
<Description>Test</Description>
<Interest>Cricekt</Interest>
<InterestId>12</InterestId>
<FeedId>4609</FeedId>
<Description>Test 2</Description>
<Interest>Read</Interest>

第一个非常适合XmlSerializer,其中擅长拉开逐项列出的xml,但对于非逐项列表却真的无济于事。阅读这样的模型往往更加手动。我可能会:

  • 确定每批次的第一个元素
  • 读到下一个元素
  • 解决两个
  • 之间的其他子元素

类似的东西:

using System;
using System.Linq;
using System.Xml.Linq;
static class Program
{
    static void Main()
    {
        var el = XDocument.Parse(xml).Root;

        var interests = from intIdEl in el.Elements("InterestId")
                        let children = intIdEl.ElementsAfterSelf().TakeWhile(
                            x => x.Name != "InterestId")
                        let feedIdEl = children.FirstOrDefault(x => x.Name == "FeedId")
                        let descIdEl = children.FirstOrDefault(x => x.Name == "Description")
                        let intEl = children.FirstOrDefault(x => x.Name == "Interest")
                        select new
                        {
                            InterestId = (int?)intIdEl,
                            FeedId = (int?)feedIdEl,
                            Description = (string)descIdEl,
                            Interest = (string)intEl
                        };

        foreach(var obj in interests)
        {
            Console.WriteLine(
              $"{obj.InterestId}, {obj.FeedId}, {obj.Description}, {obj.Interest}");
        }
    }
    const string xml = @"<Users>
<InterestId>8</InterestId><FeedId>4608</FeedId>
<Description>Test</Description> <Interest>Cricekt</Interest>
<InterestId>12</InterestId> <FeedId>4609</FeedId>
<Description>Test 2</Description> <Interest>Read</Interest>
</Users>";
}
相关问题