所以,如果我的XML看起来像这样......
<people>
<person>
<name>a</name>
</person>
<person>
<name>b</name>
</person>
</people>
将此解析为名为'people'的C#数组的最佳/最简单方法是什么?其中people [0]是第一个人对象,然后如何格式化以及如何访问它?
谢谢!
答案 0 :(得分:5)
您可以使用LINQ-To-Xml将此文件加载到数组中。
要在加载对象后简单地处理对象,您可以创建一个代表一个人的类:
public class Person
{
public string Name { get; set; }
}
然后使用XElement.Load
-method:
var document = XElement.Load("persons.xml");
var persons = document.Elements("Person")
.Select(p => new Person{ Name = p.Element("Name").Value }
.ToArray();
答案 1 :(得分:1)
您可以使用 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;}
}
答案 2 :(得分:1)
我的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);
}
}
}
}
答案 3 :(得分:0)
假设:
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();
答案 4 :(得分:0)
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();
答案 5 :(得分:0)
一行就足够了。
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>