0

我正在尝试解析一个长字符串(它实际上是一个 xml 文件)。

我熟悉子字符串,但我不知道如何遍历这个长字符串(xml 文件)并将它的子字符串分配到一个数组中。

我完全确定这是一个简单的问题,但我很难过。

4

2 回答 2

1

好吧,如果您想解析对象列表,我建议您使用LINQ TO XML

这是这个小样本:

首先是我的 XML 文件

<?xml version="1.0" encoding="utf-8" ?>
<People>
  <Person>
    <Name>Luis</Name>
    <LastName>Laurent</LastName>
    <Age>24</Age>
  </Person>
  <Person>
    <Name>Juan</Name>
    <LastName>Perez</LastName>
    <Age>24</Age>
  </Person>
  <Person>
    <Name>Karla</Name>
    <LastName>Gutierrez</LastName>
    <Age>24</Age>
  </Person>
</People>

然后是我的 .Net C# 代码

namespace Demo.Stackoverflow
{
    using System;
    using System.Linq;
    using System.Xml.Linq;

    public class Person
    {
        public string Name { get; set; }  
        public string LastName { get; set; }
        public int Age { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            ReadXML();
            Console.ReadLine();
        }

        private static void ReadXML()
        {
            string path = AppDomain.CurrentDomain.BaseDirectory + "..\\..\\Resources\\File.xml";
            XDocument doc = XDocument.Load(path);

            var People = (from people in doc.Descendants("Person")
                            select new Person()
                            {
                                Name = null != people.Descendants("Name").FirstOrDefault() ?
                                         people.Descendants("Name").First().Value : string.Empty,

                                LastName = null != people.Descendants("LastName").FirstOrDefault() ?
                                         people.Descendants("LastName").First().Value : string.Empty,

                                Age = null != people.Descendants("Age").FirstOrDefault() ?
                                         Convert.ToInt32(people.Descendants("Age").First().Value) : 0
                            }).ToList();
        }
    }
}
于 2012-12-04T20:18:41.243 回答
0

另一种选择是将 XML 反序列化为一个类。然后,您可以制作方法和属性来处理各种逻辑需求。

于 2012-12-04T18:21:48.317 回答