C#反序列化的XML文件 [英] C# Deserialization xml file

查看:163
本文介绍了C#反序列化的XML文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试反序列化xml文件:

 < XML版本=1.0编码=UTF-8 ?> 
< XMLFILE的xmlns:XSI =htt​​p://www.w3.org/2001/XMLSchema-instance的xmlns:XSD =htt​​p://www.w3.org/2001/XMLSchema>
<对象项=ItemValueTABLE_NAME =TableExample>
< /对象和GT;
< / XMLFILE>



我的反序列化类的代码看起来像:

  [Serializable接口] 
[XmlRoot(XMLFILE)]
公共类SerializeObject
{

[XmlAttribute( ITEM)]
公共字符串项{搞定;组; }

[XmlAttribute(TABLE_NAME)]
公共字符串TABLE_NAME {搞定;组; }
}

当我尝试反序列化的XML文件,我总是得到任何错误,项目和TABLE_NAME等于空。为什么呢?



THX重播


解决方案

  [XmlRoot(XMLFILE)] 
公共类SerializableContainer
{
[的XmlElement(对象)]
公共SerializeObject [] {对象得到;组; }
}

公共类SerializeObject
{
[XmlAttribute(项目)]
公共字符串项{搞定;组; }

[XmlAttribute(TABLE_NAME)]
公共字符串TABLE_NAME {搞定;组; }
}

和则与反序列化:

  VAR串=新的XmlSerializer(typeof运算(SerializableContainer)); 

使用(var文件= File.OpenText(sample.xml中))
{
VAR数据=(SerializableContainer)serializer.Deserialize(文件);

// ...
}


I try to deserialize xml file:

<?xml version="1.0" encoding="utf-8"?>
<XmlFile xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <OBJECTS ITEM="ItemValue" TABLE_NAME="TableExample">
    </OBJECTS>
</XmlFile>

My deserialize class code looks like that:

[Serializable]
[XmlRoot("XmlFile")]
public class SerializeObject
{

    [XmlAttribute("ITEM")]
    public string Item { get; set; }

    [XmlAttribute("TABLE_NAME")]
    public string Table_Name { get; set; }
}

When I try deserialize xml file i always got no errors and Item and Table_Name equals null. Why?

Thx for replay

解决方案

[XmlRoot("XmlFile")]
public class SerializableContainer
{
    [XmlElement("OBJECTS")]
    public SerializeObject[] Objects { get; set; }
}

public class SerializeObject
{
    [XmlAttribute("ITEM")]
    public string Item { get; set; }

    [XmlAttribute("TABLE_NAME")]
    public string Table_Name { get; set; }
}

And then you deserialize with:

var serializer = new XmlSerializer(typeof(SerializableContainer));

using (var file = File.OpenText("sample.xml"))
{
    var data = (SerializableContainer)serializer.Deserialize(file);

    // ... 
}

这篇关于C#反序列化的XML文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆