开发者

Converting xml object hierarchy to objects and adding to a list

I am new to xml , so please don't mind if it is too trivial question

Assume I have a xml file like below

 <Person>       
        <Name>John-Jaime-Winston Junior</Name>       
    </Person>
    <Person>       
        <Name>Steve</Name>
    </person   

Now i will have a person object , Can i know how to rea开发者_StackOverflowd the xml and cover to a array of objects.

Finally i want something like a list which will have all person objects.

I am unable to get the start how to do this as i am new to xml

class person {

 string _name

 public string Name
        {
            get { return _name}
            set { _name= value; }
        }

}

Thanks in advance


Given .NET 3.5 and System.Xml.Linq this is quite easy.

var q = from e in XElement.Parse(xml).Elements()
        select new Person() { 
            Name = e.Element("Name").Value 
        };

var p = q.ToList();

You will need to provide valid XML like what follows:

<People>
    <Person>
        <Name>Jim</Name>
    </Person>
    <Person>
        <Name>Bill</Name>
    </Person>
</People>


I think you want something like XmlSerializer, you can serialize and deserialize objects by this. just should define properties public

[Serializable()]
public class person 
{

        string _name

        public string Name
        {
            get { return _name}
            set { _name= value; }
        }

}

and use it:

        XmlSerializer serializer = new XmlSerializer(typeof(Person));
        StreamWriter sw = new StreamWriter("c:\\out.xml");
        serializer.Serialize(sw,new Person{Name = "Test"});
        sw.Close();


        StreamReader sr = new StreamReader("c:\\out.xml");
        var outVal = serializer.Deserialize(sr) as Person;

But for parsing xml in normal way you can use XDocument or XPath, ...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜