具体解析XML到一个数组 [英] Specific parsing XML into an array

查看:143
本文介绍了具体解析XML到一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,如果我有XML,看起来是这样的....

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

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

什么是分析此为C#阵列称为最好/最简单的方法'人'那里的人[0]是第一人称对象,然后会是怎样被格式化,我将如何去访问它?

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?

谢谢!

推荐答案

我的C#是生锈的,不过这是很简单的使用 XML序列化

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);
            }
        }
    }
}

这篇关于具体解析XML到一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆