开发者

Mapping XML data to class in C#

If I have an external XML feed and an internal class, w开发者_运维技巧hat is the best way to automatically read the feed and map the data to new instances of the class?

So if the xml feed is like

<people>
   <person>
      <name>Bob</name>
   </person>
    <person>
      <name>Bill</name>
   </person>
</people>

And my class Person has a property Name. Right now I am stepping through with XmlReader but this seems inefficient


The easiest way to map xml into a class in c# is using xml serialization. The -.Net framework comes with everything you need. The problem is, that your xml need to be in the rigth format to be read by the deserializer.

Serialization Example:

  XmlSerializer serializer = new XmlSerializer(typeof(List<Person>));
  TextWriter textWriter = new StreamWriter("people.xml");
  serializer.Serialize(textWriter, people);
  textWriter.Close();

Deserialization Example

   XmlSerializer deserializer = new XmlSerializer(typeof(List<Person>));
   TextReader textReader = new StreamReader("people.xml");
   List<Person> people; 
   people= (List<Person>)deserializer.Deserialize(textReader);
   textReader.Close();

XML Result

The xml should look like this (I didn't test it):

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfPerson xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Person>
    <Name>Bob</Name>
  </Person>
  <Person>
    <Name>Bill</Name>
  </Person>
</ArrayOfPerson>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜