在C#中将xml转换为动态对象

时间:2012-08-09 07:36:58

标签: c# asp.net xml

在我的网络应用程序中,我在这样的网页浏览器上显示结果为xml

<Responses>
<Response0>
    <Action>sendMessage</Action>
    <Data>
        <AcceptReport>
            <StatusCode>0</StatusCode>
            <StatusText>Message accepted for delivery</StatusText>
            <MessageID>89c8011c-e291-44c3-ac72-cd35c76cb29d</MessageID>
            <Recipient>+85568922903</Recipient>
        </AcceptReport>
    </Data>
</Response0>
</Responses>

我希望上面的XML文件显示如下文所示:

Message accepted for delivery
Message ID: IEUHSHIL
Recipient: +441234567

如何将xml文件转换为上面的文本?

1 个答案:

答案 0 :(得分:3)

修改

源代码

XDocument doc = XDocument.Parse("<Responses> <Response0>     <Action>sendMessage</Action>     <Data>         <AcceptReport>             <StatusCode>0</StatusCode>             <StatusText>Message accepted for delivery</StatusText>             <MessageID>89c8011c-e291-44c3-ac72-cd35c76cb29d</MessageID>             <Recipient>+85568922903</Recipient>         </AcceptReport>     </Data> </Response0> </Responses> ");

var message = from item in doc.Descendants("AcceptReport")
               select new { 
                    StatusText = item.Element("StatusText").Value,
                    MessageID = item.Element("MessageID").Value,
                    Recipient = item.Element("Recipient").Value 
               };
foreach (var el in message)
{
    Console.WriteLine(el.MessageID + " " +el.Recipient + " " + el.StatusText);
}

注意:如果要传递字符串而不是xml文件,请使用XDocument.Parse


简单的方法是使用Linq To XML

检查那里:Reading XML documents using LINQ to XML

不确定但是这样的事情

var message=  
              from item in XElement.Load("message.xml").Descendants("Data") 
                 select new
                 {
                      StatusText= item.Element("StatusText").Value,
                      MessageID= item.Element("MessageID").Value,
                      Recipient= item.Element("Recipient").Value
                  };