如何从 XML 重建 C# 类

发布于 2024-09-05 04:29:01 字数 109 浏览 7 评论 0原文

我想在 SQL 中保存 ac#.NET 类的实例以供以后检索。我能够使用 LINQ to SQL 添加包含构成该类的所有 xml 的完整记录。

现在我如何检索该 xml 并重建类对象实例?

I would like to save an instance of a c#.NET class in SQL for later retrieval. I am able to use LINQ to SQL to add a record complete with all the xml that makes up the class.

Now how do I retrieve that xml and reconstruct the class object instance?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

挽清梦 2024-09-12 04:29:01

将对象序列化为 XML 字符串:

    public static string ToXml<T>(T obj)
    {
        XmlWriterSettings settings = new XmlWriterSettings();

        settings.OmitXmlDeclaration = true;
        using (Stream stream = new MemoryStream())
        using (XmlWriter writer = XmlWriter.Create(stream, settings))
        {
            new XmlSerializer(obj.GetType()).Serialize(writer, obj);
            writer.Flush();
            stream.Flush();
            stream.Position = 0;
            using (TextReader reader = new StreamReader(stream))
            {
                return reader.ReadToEnd();
            }
        }
    }

将 XML 字符串反序列化为对象:

    public static T FromXml<T>(string xml)
    {
        using (TextReader reader = new StringReader(xml))
        {
            try
            {
                return (T)new XmlSerializer(typeof(T)).Deserialize(reader);
            }
            catch (InvalidOperationException)
            {
                // string passed is not XML, return default
                return default(T);
            }
        }
    }

Serialize your object to an XML string:

    public static string ToXml<T>(T obj)
    {
        XmlWriterSettings settings = new XmlWriterSettings();

        settings.OmitXmlDeclaration = true;
        using (Stream stream = new MemoryStream())
        using (XmlWriter writer = XmlWriter.Create(stream, settings))
        {
            new XmlSerializer(obj.GetType()).Serialize(writer, obj);
            writer.Flush();
            stream.Flush();
            stream.Position = 0;
            using (TextReader reader = new StreamReader(stream))
            {
                return reader.ReadToEnd();
            }
        }
    }

Deserialize an XML string into an object:

    public static T FromXml<T>(string xml)
    {
        using (TextReader reader = new StringReader(xml))
        {
            try
            {
                return (T)new XmlSerializer(typeof(T)).Deserialize(reader);
            }
            catch (InvalidOperationException)
            {
                // string passed is not XML, return default
                return default(T);
            }
        }
    }
命硬 2024-09-12 04:29:01

正如其他人提到的,序列化可以解决问题,但要注意格式化程序/序列化程序,否则:

将是序列化的一部分。只要有可能,请使用 DataContractSerializer。

我强烈建议您查看以下内容: .NET XML Serialization without 在执行任何操作之前进行文本声明

华泰

As others mention, serialization will do the trick, but be aware of the formatters/serializer, otherwise this :

<?xml version="1.0" encoding="utf-8" ?>

will be part of your serialization. Whenever possible, use the DataContractSerializer.

I highly recommend you to see this : .NET XML Serialization without <?xml> text declaration before doing anything.

HTH

彩扇题诗 2024-09-12 04:29:01

您可能需要使用 XStream 将对象存储为 XML。它非常容易使用。

You might want to use XStream to store the object as XML. It's pretty easy to use.

长不大的小祸害 2024-09-12 04:29:01

我建议使用 xml 序列化和反序列化。

如果我定义了一个 Person 类:

public class Person
{
    public int ID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime DateOfBirth { get; set; }
}

保存它/从 XML 加载它就像这样简单:

Person donald = new Person{
                ID=1, 
                FirstName="Donald", 
                LastName="Duck", 
                DateOfBirth=new DateTime(1950,1,1)};

//create a xml serializer with the required type
XmlSerializer xs=new XmlSerializer(typeof(Person));

//open a stream to the file, and save the instance
TextWriter tw = new StreamWriter(@"C:\donald.xml");
xs.Serialize(tw, donald);
tw.Close();

//open a reader stream to the file, and just load the instance.
TextReader tr = new StreamReader(@"C:\donald.xml");
Person donald2 = (Person) xs.Deserialize(tr);
tr.Close();

警告:这仅将类的公共属性/字段保存为 XML 元素。如果要对生成的 XML 进行附加控制,请查看 System.Xml.Serialization 命名空间(XmlAttributeAttribute 是我个人最喜欢的),

I would recommend xml serialization and deserialization.

If I have a class Person defined with:

public class Person
{
    public int ID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime DateOfBirth { get; set; }
}

saving it/loading it from XML is as simple as:

Person donald = new Person{
                ID=1, 
                FirstName="Donald", 
                LastName="Duck", 
                DateOfBirth=new DateTime(1950,1,1)};

//create a xml serializer with the required type
XmlSerializer xs=new XmlSerializer(typeof(Person));

//open a stream to the file, and save the instance
TextWriter tw = new StreamWriter(@"C:\donald.xml");
xs.Serialize(tw, donald);
tw.Close();

//open a reader stream to the file, and just load the instance.
TextReader tr = new StreamReader(@"C:\donald.xml");
Person donald2 = (Person) xs.Deserialize(tr);
tr.Close();

Caveat: This saves only the public properties/fields of a class, as XML Elements. If you want to exercise addition control over the generated XML, take a look at the attributes in the System.Xml.Serialization namespace (XmlAttributeAttribute is my personal favorite),

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文