将xml字符串转换为我的Object列表

  http://www.examiner.com/ 34   http://www.sample123.com 16   http://www.testing123.com 14   

我在字符串中有上面的xml,我有类似下面的类

 public class Row { public string linksclicked { get; set; } public int clickedcount { get; set; } } 

如何将xml字符串转换为行对象列表

您可以使用LINQ to XML:

 var doc = XDocument.Parse(xmlString); var items = (from r in doc.Root.Elements("row") select new Row() { linksclicked = (string) r.Element("linksclicked"), clickedcount = (int) r.Element("clickedcount") }).ToList(); 

你可以尝试这段代码

 string xml = "12"; ArrayList list = new ArrayList(); XmlDocument doc = new XmlDocument(); doc.LoadXml(xml); XmlNodeList idNodes = doc.SelectNodes("Ids/id"); foreach (XmlNode node in idNodes) list.Add(node.InnerText); 

您可以使用XMLSerializer反序列化List类型的属性,并将标记名称作为root分配给属性。

但是,您需要在文件的开头添加XML标记。

你可以使用XElement编写自己的XML解析器。 您可以在行节点列表中解析每个行节点,然后将它们加载到列表中。

 XElement rootNode = XElement.Load(filepath); List nodes = rootNode.Descendants().Where(t=> t.Name.ToString().Equals("row")); 

对于每个标记,您可以创建一个对象Row并根据子标记填充其属性。 希望能帮助到你

如果xml结果从服务器调用变为空,则此方法可以更安全地避免exception。

 string xmlString = "2dummy
12
3dummy
11
"; XDocument doc = new XDocument(); //Check for empty string. if (!string.IsNullOrEmpty(xmlString)) { doc = XDocument.Parse(xmlString); } List students = new List(); //Check if xml has any elements if(!string.IsNullOrEmpty(xmlString) && doc.Root.Elements().Any()) { students = doc.Descendants("Student").Select(d => new Student { id=d.Element("Id").Value, name=d.Element("Name").Value, section=d.Element("Section").Value }).ToList(); } public class Student{public string id; public string name; public string section;}

检查演示小提琴演示

试试这个:

 var xml = @"   http://www.examiner.com/ 34   http://www.sample123.com 16   http://www.testing123.com 14  "; var xElems = XDocument.Parse(xmlString); var xRow = doc.Root.Elements("row"); List rowList = (from rowTags in xRow let clickCount = 0 let isClickCountOk = Int32.TryParse((rowTags.Element("clickedcount").Value, clickCount); where !string.IsNullOrEmpty(rowTags.Element("linksclicked").Value) && !string.IsNullOrEmpty(rowTags.Element("clickedcount").Value) select new Row() { linksclicked = rowTags.Element("linksclicked").Value, clickedcount = clickCount }).ToList();