2014-11-24 132 views
0

我正在使用WebRequest和WebReponse类从Web API获取响应。我得到的回应是以下格式如何将xml字符串转换为使用c的对象#

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

<ROOT> 
    <A></A> 
    <B></B> 
    <C></C> 
    <D> 
     <E NAME="aaa" EMAIL="[email protected]"/> 
     <E NAME="bbb" EMAIL="[email protected]"/> 
    </D> 
</ROOT> 

我想所有的E元素作为List<E>或东西的XML。

有人可以指导我这个请求。

+0

上课for xml并使用XmlSerialization Deserialize方法将xml转换为该新创建类的对象 - http://msdn.microsoft.com/en-us/library/dsh84875%28v=vs.110%29.aspx – malkam 2014-11-24 13:40:17

回答

4

,如果你想避免序列化,因为你只希望XML的一个非常具体的部分,你可以用一个LINQ语句来做到这一点:

var items = XDocument.Parse(xml) 
       .Descendants("E") 
       .Select(e => new 
       { 
        Name = e.Attribute("NAME").Value, 
        Email = e.Attribute("EMAIL").Value 
       }) 
       .ToList(); 
+0

perfecto。为了增加他,我更喜欢使用'.Descendants(“D”) .Descendants(“E”)'这样如果所有元素都被添加到xml输出的其他地方,我的代码就不会中断。谢谢 – Yasser 2014-11-25 05:25:36

0

工作例如:

var doc = XDocument.Parse(@"<?xml version='1.0' encoding='UTF-8'?> 
<ROOT> 
    <A></A> 
    <B></B> 
    <C></C> 
    <D> 
     <E NAME='aaa' EMAIL='[email protected]'/> 
     <E NAME='bbb' EMAIL='[email protected]'/> 
    </D> 
</ROOT>"); 

      var elements = from el in doc.Elements() 
          from el2 in el.Elements() 
          from el3 in el2.Elements() 
          where el3.Name == "E" 
          select el3; 
      foreach (var e in elements) 
      { 
       Console.WriteLine(e); 
      } 
相关问题