• Xml Deserialize


    C#:

    XmlDeserialize<C, Cs>(rdr["Cs"]))


    public List<T> XmlDeserialize<T, TList>(string xmlString)
    {
    var results = new List<T>();
    if (!string.IsNullOrEmpty(xmlString))
    {
    XmlSerializer xs = new XmlSerializer(typeof(TList));
    XmlTextReader reader = new XmlTextReader(new System.IO.StringReader(xmlString));

    results = (List<T>)xs.Deserialize(reader);
    }

    return results;
    }


    [XmlType("C")]
    public class C
    {
    public string CId { get; set; }
    }

    [Serializable()]
    [XmlRoot("ROOT")]
    public class Cs:List<C>
    {
    }

    sql:

    select name,(select cid from tb1 For XML PATH('Contacts'),ROOT('ROOT'))xmlrow from tb

    <ROOT>

      <Cs><CId>1</CId></Cs>

      <Cs><CId>2</CId></Cs>

    </ROOT>

    --------------------

    [Serializable()]
    public class Car
    {
        [System.Xml.Serialization.XmlElement("StockNumber")]
        public string StockNumber { get; set; }
    
        [System.Xml.Serialization.XmlElement("Make")]
        public string Make { get; set; }
    
        [System.Xml.Serialization.XmlElement("Model")]
        public string Model { get; set; }
    }
    
    
    [Serializable()]
    [System.Xml.Serialization.XmlRoot("CarCollection")]
    public class CarCollection
    {
        [XmlArray("Cars")]
        [XmlArrayItem("Car", typeof(Car))]
        public Car[] Car { get; set; }
    }

    The Deserialize function:

    CarCollection cars = null;
    string path = "cars.xml";
    
    XmlSerializer serializer = new XmlSerializer(typeof(CarCollection));
    
    StreamReader reader = new StreamReader(path);
    cars = (CarCollection)serializer.Deserialize(reader);
    reader.Close();

    And the slightly tweaked xml (I needed to add a new element to wrap <Cars>...Net is picky about deserializing arrays):

    <?xml version="1.0" encoding="utf-8"?>
    <CarCollection>
    <Cars>
      <Car>
        <StockNumber>1020</StockNumber>
        <Make>Nissan</Make>
        <Model>Sentra</Model>
      </Car>
      <Car>
        <StockNumber>1010</StockNumber>
        <Make>Toyota</Make>
        <Model>Corolla</Model>
      </Car>
      <Car>
        <StockNumber>1111</StockNumber>
        <Make>Honda</Make>
        <Model>Accord</Model>
      </Car>
    </Cars>
    </CarCollection>
  • 相关阅读:
    js中使用EL表达式
    洛谷——RMQ
    模板——RMQ
    洛谷——图论
    洛谷——基础搜索
    洛谷——搜索
    搭桥
    简单dp
    Codevs 3194 基因变异
    cin、scanf、gets、getchar 用法介绍
  • 原文地址:https://www.cnblogs.com/likem/p/4289766.html
Copyright © 2020-2023  润新知