C# 如何使用c将xml字符串转换为对象

C# 如何使用c将xml字符串转换为对象,c#,asp.net,xml-serialization,jsonserializer,C#,Asp.net,Xml Serialization,Jsonserializer,我使用WebRequest和WebResponse类从web api获取响应。我得到的响应是以下格式的xml <?xml version="1.0" encoding="UTF-8"?> <ROOT> <A></A> <B></B> <C></C> <D> <E NAME="aaa" EMAIL="a@a.com"/>

我使用WebRequest和WebResponse类从web api获取响应。我得到的响应是以下格式的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>
我想把所有的E元素都列成一个列表之类的


有人能在这方面指导我吗

如果您希望避免序列化,因为您只需要xml的一个非常特定的部分,那么可以使用一条LINQ语句:

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

如果要避免序列化,因为您只需要xml的一个非常特定的部分,可以使用一条LINQ语句:

var items = XDocument.Parse(xml)
              .Descendants("E")
              .Select(e => new 
                 {
                    Name = e.Attribute("NAME").Value, 
                    Email = e.Attribute("EMAIL").Value
                 })
              .ToList();
工作示例:

 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);
            }
工作示例:

 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);
            }

拥有xml类并使用XmlSerialization反序列化方法将xml转换为新创建类的对象-拥有xml类并使用XmlSerialization反序列化方法将xml转换为新创建类的对象-perfecto。为了添加到他身上,我更喜欢使用.degenantsd.degenantse,这样,如果在xml输出的任何其他地方添加了元素E,我的代码就不会中断。谢谢你。为了添加到他身上,我更喜欢使用.degenantsd.degenantse,这样,如果在xml输出的任何其他地方添加了元素E,我的代码就不会中断。谢谢