Specific parsing XML into an array

2019-06-07 23:05发布

So if I have XML that looks something like this....

<people>
    <person>
        <name>a</name>
    </person>
    <person>
        <name>b</name>
    </person>
</people>

What's the best/easiest way to parse this into a C# array called 'people' where people[0] is the first person object, and then how would it be formatted and how would I go about accessing it?

Thanks!

6条回答
欢心
2楼-- · 2019-06-07 23:18

My C# is rusty, but this is simple enough using XML serialization

Deserializing (reading), modifying, then serializing (writing):

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);
            }
        }
    }
}
查看更多
Lonely孤独者°
3楼-- · 2019-06-07 23:20
var doc = XDocument.Parse(input);
string[] names = doc.Root.Descendants("name").Select(x => x.Value).ToArray();

If the input xml format is as simple as the one you provided the above statement is sufficient, otherwise add this where clause to not capture other name elements in your xml file:

string[] names = doc.Root.Descendants("name")
                        .Where(x => x.Parent.Name == "person")
                        .Select(x => x.Value).ToArray();
查看更多
Ridiculous、
4楼-- · 2019-06-07 23:22

You could use LINQ-To-Xml to load this file into an array.

To simply handle the object after loading them you could create a class representing a person:

public class Person
{
    public string Name { get; set; }
} 

Then load the file using the XElement.Load-method:

var document = XElement.Load("persons.xml");
var persons = document.Elements("Person")
    .Select(p => new Person{ Name = p.Element("Name").Value }
    .ToArray();
查看更多
Ridiculous、
5楼-- · 2019-06-07 23:31

You can do it easily with LinqToXml:

var doc = XDocument.Parse(myXmlString); // .Load("filepath");
var persons = doc.Root
                 .Elements("Person")
                 .Select(x=> new Person {Name= x.Element("Name").Value})
                 .ToArray();

It will return you an array of Person's defined as below.

Person

public class Person{
     public string Name {get; set;}
}
查看更多
唯我独甜
6楼-- · 2019-06-07 23:33

Assuming:

class Person
{
    public string Name { get; set; }
}

Then (query syntax):

var arr = (from p in XDocument.Load(path) // or .Parse(str)
                              .Root
                              .Elements("person")
           select new Person
           {
               Name = (string)p.Attribute("name")
           }).ToArray();

The same in Extension Methods syntax:

XDocument.Load(path)
         .Root
         .Elements("person")
         .Select(p => new new Person
             {
                 Name = (string)p.Attribute("name")
             })
         .ToArray();
查看更多
趁早两清
7楼-- · 2019-06-07 23:37

One line is enough.

var people=XDocument.Load(path).Root.Elements().Select(y => y.Elements().ToDictionary(x => x.Name, x => x.Value)).ToArray();

You need to specify following namespaces for testing

using System.Xml.Linq;
using System.Collections.Generic;
using System.Collections;
using System.Linq;

test code

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
}

the sample xml for test

<people>
    <person>
        <name>Humbert Humbert</name>
        <age>36</age>
    </person>

    <person>
        <name>Lolita</name>
        <age>12</age>
    </person>
</people>
查看更多
登录 后发表回答