因此,如果我有类似这样的XML。。。。
<people>
<person>
<name>a</name>
</person>
<person>
<name>b</name>
</person>
</people>
将其解析为一个名为"people"的C#数组的最佳/最简单方法是什么,其中people[0]是第一人称对象,然后如何格式化它,以及如何访问它?
谢谢!
您可以使用LINQ To Xml将此文件加载到数组中。
为了在加载对象后简单地处理它们,您可以创建一个代表一个人的类:
public class Person
{
public string Name { get; set; }
}
然后使用XElement.Load
-方法加载文件:
var document = XElement.Load("persons.xml");
var persons = document.Elements("Person")
.Select(p => new Person{ Name = p.Element("Name").Value }
.ToArray();
我的C#有些生疏,但使用XML序列化就足够简单了
反序列化(读取),修改,然后序列化(写入):
using System;
using System.IO;
using System.Xml.Serialization;
namespace ConsoleApplication1
{
[XmlRoot("people")]
public class People
{
[XmlElement("person")]
public Person[] person { get; set; }
}
[Serializable]
public class Person
{
[XmlElement("name")]
public string Name { get; set; }
}
class Program
{
public static void Main(string[] args)
{
People people = null;
XmlSerializer serializer = new XmlSerializer(typeof(People));
using (StreamReader reader = new StreamReader("people.xml"))
{
people = (People)serializer.Deserialize(reader);
}
people.person[0].Name = "Dan";
using (StreamWriter writer = new StreamWriter("people.xml"))
{
serializer.Serialize(writer, people);
}
}
}
}
使用LinqToXml:可以轻松完成
var doc = XDocument.Parse(myXmlString); // .Load("filepath");
var persons = doc.Root
.Elements("Person")
.Select(x=> new Person {Name= x.Element("Name").Value})
.ToArray();
它将返回一个Person
的数组,定义如下。
人员
public class Person{
public string Name {get; set;}
}
假设:
class Person
{
public string Name { get; set; }
}
然后(查询语法):
var arr = (from p in XDocument.Load(path) // or .Parse(str)
.Root
.Elements("person")
select new Person
{
Name = (string)p.Attribute("name")
}).ToArray();
扩展方法语法相同:
XDocument.Load(path)
.Root
.Elements("person")
.Select(p => new new Person
{
Name = (string)p.Attribute("name")
})
.ToArray();
var doc = XDocument.Parse(input);
string[] names = doc.Root.Descendants("name").Select(x => x.Value).ToArray();
如果输入的xml格式和您提供的格式一样简单,那么上面的语句就足够了,否则添加where子句以不捕获xml文件中的其他name
元素:
string[] names = doc.Root.Descendants("name")
.Where(x => x.Parent.Name == "person")
.Select(x => x.Value).ToArray();
一行就足够了。
var people=XDocument.Load(path).Root.Elements().Select(y => y.Elements().ToDictionary(x => x.Name, x => x.Value)).ToArray();
您需要指定以下命名空间来测试
using System.Xml.Linq;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
测试代码
var path=@"c:people.xml";
var people=XDocument.Load(path).Root.Elements().Select(y => y.Elements().ToDictionary(x => x.Name, x => x.Value)).ToArray();
foreach(var person in people) {
Console.WriteLine("name = {0}", person["name"]);
Console.WriteLine("name = {0}", person["age"]); // requires person have a age defined in your xml file
}
用于测试的示例xml
<people>
<person>
<name>Humbert Humbert</name>
<age>36</age>
</person>
<person>
<name>Lolita</name>
<age>12</age>
</person>
</people>