[英]How to convert xml string to an object using c#
I am using WebRequest and WebReponse classes to get a response from a web api. 我正在使用WebRequest和WebReponse类从Web api获取响应。 The response I get is an xml of the following format 我得到的响应是以下格式的xml
<?xml version="1.0" encoding="UTF-8"?>
<ROOT>
<A></A>
<B></B>
<C></C>
<D>
<E NAME="aaa" EMAIL="a@a.com"/>
<E NAME="bbb" EMAIL="b@b.com"/>
</D>
</ROOT>
I want to get all the E
elements as a List<E>
or something. 我想以List<E>
方式获取所有E
元素。
Can some one guide me on this pls. 有人可以指导我吗?
if you want to avoid serialization, as you only want a very specific part of the xml, you can do this with one LINQ statement: 如果要避免序列化,因为只需要xml的非常特定的部分,则可以使用一个LINQ语句来做到这一点:
var items = XDocument.Parse(xml)
.Descendants("E")
.Select(e => new
{
Name = e.Attribute("NAME").Value,
Email = e.Attribute("EMAIL").Value
})
.ToList();
Working example: 工作示例:
var doc = XDocument.Parse(@"<?xml version='1.0' encoding='UTF-8'?>
<ROOT>
<A></A>
<B></B>
<C></C>
<D>
<E NAME='aaa' EMAIL='a@a.com'/>
<E NAME='bbb' EMAIL='b@b.com'/>
</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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.