简体   繁体   English

如何将字符串中包含的 XML 解析为 IList<businessobject> ?</businessobject>

[英]How to parse XML contained in a string to an IList<BusinessObject>?

I have the following XML in a string:我在字符串中有以下 XML :

<RootElement>
  <Data>
    <Row>
      <id>1</id>
      <name>Foo</name>
    </Row>
    <Row>
      <id>2</id>
      <name>Bar</name>
    </Row>
       .
       .
       .
  </Data>
</RootElement>

And the following class:以及以下 class:

public class BusinessObject
{
    public int Id { get; set; }
    public string Name { get; set; }
}

How can i parse all the data in the Row elements to an IList ( in C# )?如何将 Row 元素中的所有数据解析为 IList(在 C# 中)? I searched the internet a few hours but couldn't find anything to solve this problem.我在互联网上搜索了几个小时,但找不到任何解决此问题的方法。 Thanks in advance for your answers提前感谢您的回答

One option, using LINQ to XML:一种选择,使用 LINQ 到 XML:

XDocument doc = XDocument.Load(...);
var businessObjects = doc.Descendants("Row")
                         .Select(x => new BusinessObject {
                                     Id = (int) x.Element("id"),
                                     Name = (string) x.Element("name")
                                 })
                         .ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM