How do I map XML to C# objects

前端 未结 9 1845
旧巷少年郎
旧巷少年郎 2020-11-27 13:37

I have an XML that I want to load to objects, manipulate those objects (set values, read values) and then save those XMLs back. It is important for me to have the XML in the

相关标签:
9条回答
  • 2020-11-27 14:04

    You can generate serializable C# classes from a schema (xsd) using xsd.exe:

    xsd.exe dependency1.xsd dependency2.xsd schema.xsd /out:outputDir
    

    If the schema has dependencies (included/imported schemas), they must all be included on the same command line.

    0 讨论(0)
  • 2020-11-27 14:05

    This code (C# DotNet 1.0 onwards) works quite well to serialize most objects to XML. (and back) It does not work for objects containing ArrayLists, and if possible stick to using only Arrays

    using System;    
    using System.IO;
    using System.Text;
    using System.Xml.Serialization;
    using System.Runtime.Serialization;
    using System.Runtime.Serialization.Formatters.Binary;
    
    
    public static string Serialize(object objectToSerialize)
    {
        MemoryStream mem = new MemoryStream();          
        XmlSerializer ser = new XmlSerializer(objectToSerialize.GetType());         
        ser.Serialize(mem, objectToSerialize);                      
        ASCIIEncoding ascii = new ASCIIEncoding();
        return ascii.GetString(mem.ToArray());
    }        
    
    public static object Deserialize(Type typeToDeserialize, string xmlString)
    {
        byte[] bytes = Encoding.UTF8.GetBytes(xmlString);
        MemoryStream mem = new MemoryStream(bytes);         
        XmlSerializer ser = new XmlSerializer(typeToDeserialize);
        return ser.Deserialize(mem);
    }
    
    0 讨论(0)
  • 2020-11-27 14:14

    I'll bet NetDataContractSerializer can do what you want.

    0 讨论(0)
提交回复
热议问题