将XML解析为对象

时间:2013-06-28 18:25:21

标签: c# xml linq

这是XML:

  <?xml version="1.0" encoding="utf-8" ?> 
  <object>
    <body>tests</body> 
    <send_results type="null" /> 
    <note_class>none</note_class> 
    <users type="list" /> 
    <title>test</title> 
    <time_sent type="null" /> 
    <image type="null" /> 
    <to_customers type="boolean">False</to_customers> 
    <time_created>2013-06-26T16:40:50</time_created> 
    <num_sends type="integer">0</num_sends> 
    <time_scheduled type="null" /> 
    <dealership>/api/v1/dealerships/10/</dealership> 
    <id type="integer">22</id> 
    <send_rate>none</send_rate> 
    <send_method>email</send_method> 
    <reply_to_email>do_not_reply@williamson-cadillac.com</reply_to_email> 
    <response_link type="null" /> 
    <to_users type="boolean">True</to_users> 
    <resource_uri>/api/v1/notifications/22/</resource_uri> 
  </object>

我正在尝试将Xml解析为对象......

       var query = from m in parsedXml.Decendants("object")
                    select new Notifications
                    {
                        Body = (string)m.Element("body"),
                        SendResults = (string)m.Element("send_results"),
                        NoteClass = (string)m.Element("note_class"),
                        Users = m.Element("users").Elements().Select(e => (string)e.Element("value")).ToList(),
                        Title = (string)m.Element("title"),
                        TimeSent = (string)m.Element("time_sent"),
                        Image = (string)m.Element("image"),
                        ToCustomers = (string)m.Element("to_customers"),
                        TimeCreated = (string)m.Element("time_created"),
                        NumSends = (string)m.Element("num_sends"),
                        TimeScheduled = (string)m.Element("time_scheduled"),
                        Dealership = (string)m.Element("dealership"),
                        Id = (string)m.Element("id"),
                        SendRate = (string)m.Element("send_rate"),
                        SendMethod = (string)m.Element("send_method"),
                        ReplyToEmail = (string)m.Element("reply_to_email"),
                        ResponseLink = (string)m.Element("response_link"),
                        ToUsers = (string)m.Element("to_users"),
                        ResourceUri = (string)m.Element("resource_uri"),
                    };

我继续在变量“query”中获得“nothing”或“null”。

我无法弄清楚这一点 - 我尝试过许多不同的事情。谢谢你帮助解决这些问题。

2 个答案:

答案 0 :(得分:2)

我复制了您的代码并将其直接粘贴到控制台应用程序中。它完全按预期工作。

enter image description here

您可以向我们展示可能对结果产生影响的其他内容吗?

以下是我使用的完整示例,以防您做不同的事情......

string xml = 
@"<?xml version='1.0' encoding='utf-8' ?> 
  <object>
    <body>tests</body> 
    <send_results type='null' /> 
    <note_class>none</note_class> 
    <users type='list' /> 
    <title>test</title> 
    <time_sent type='null' /> 
    <image type='null' /> 
    <to_customers type='boolean'>False</to_customers> 
    <time_created>2013-06-26T16:40:50</time_created> 
    <num_sends type='integer'>0</num_sends> 
    <time_scheduled type='null' /> 
    <dealership>/api/v1/dealerships/10/</dealership> 
    <id type='integer'>22</id> 
    <send_rate>none</send_rate> 
    <send_method>email</send_method> 
    <reply_to_email>do_not_reply@williamson-cadillac.com</reply_to_email> 
    <response_link type='null' /> 
    <to_users type='boolean'>True</to_users> 
    <resource_uri>/api/v1/notifications/22/</resource_uri> 
  </object>";
var parsedXml = XDocument.Parse(xml);
var query = from m in parsedXml.Descendants("object")
            select new Notifications
            {
                Body = (string)m.Element("body"),
                SendResults = (string)m.Element("send_results"),
                NoteClass = (string)m.Element("note_class"),
                Users = m.Element("users").Elements().Select(e => (string)e.Element("value")).ToList(),
                Title = (string)m.Element("title"),
                TimeSent = (string)m.Element("time_sent"),
                Image = (string)m.Element("image"),
                ToCustomers = (string)m.Element("to_customers"),
                TimeCreated = (string)m.Element("time_created"),
                NumSends = (string)m.Element("num_sends"),
                TimeScheduled = (string)m.Element("time_scheduled"),
                Dealership = (string)m.Element("dealership"),
                Id = (string)m.Element("id"),
                SendRate = (string)m.Element("send_rate"),
                SendMethod = (string)m.Element("send_method"),
                ReplyToEmail = (string)m.Element("reply_to_email"),
                ResponseLink = (string)m.Element("response_link"),
                ToUsers = (string)m.Element("to_users"),
                ResourceUri = (string)m.Element("resource_uri"),
            };

Console.WriteLine("Number of items = {0}, {1}",query.Count(), query.FirstOrDefault().Body);
Console.ReadLine(); 

答案 1 :(得分:0)

您尚未显示正在解析的XML,我们理所当然地认为它已正确完成。可以肯定的是,您应该从文件加载它或解析这样的字符串。

//Load Xml file
var document = XDocument.Load(@"c:\temp\test.xml");

//Parse Xml 
var document = XDocument.Parse(xml);

如果您在开始var query的行上放置一个断点,那么当它点击parsedXml以确保它具有预期值时。

此外你应该有这样的东西,你现在缺少一个根节点。

  <?xml version="1.0" encoding="utf-8" ?> 
  <objects>
     <object>
         ...
     <object>
  </objects>

最后,如果您已经有一个正确反序列化的类,则使用LINQ与反序列化不同。如果您只是选择现有的类,那么LINQ就是您想要的。确保您使用的是正确的工具。