Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将C#类序列化为xml。将XML作为字符串存储在SQL Server中,然后稍后还原该类_C#_.net_Xml Serialization - Fatal编程技术网

将C#类序列化为xml。将XML作为字符串存储在SQL Server中,然后稍后还原该类

将C#类序列化为xml。将XML作为字符串存储在SQL Server中,然后稍后还原该类,c#,.net,xml-serialization,C#,.net,Xml Serialization,我想将一个类序列化为xml,并将其存储在数据库的一个字段中。我可以用以下命令序列化: StringWriter sw = new StringWriter(); XmlSerializer xmlser = new XmlSerializer(typeof(MyClass)); xmlser.Serialize(sw, myClassVariable); string s = sw.ToString(); sw.Close(); 这是可行的,但它有名称空间 <.... xmlns:xs

我想将一个类序列化为xml,并将其存储在数据库的一个字段中。我可以用以下命令序列化:

StringWriter sw = new StringWriter();
XmlSerializer xmlser = new XmlSerializer(typeof(MyClass));

xmlser.Serialize(sw, myClassVariable);
string s = sw.ToString();
sw.Close();
这是可行的,但它有名称空间

<.... xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
      xmlns:xsd="http://www.w3.org/2001/XMLSchema">

这些是否会减慢反序列化的速度,因为反序列化将用于验证XML?我通过创建一个空白的XmlSerializerNamespaces并使用它进行序列化来摆脱名称空间,但是xml仍然在整数变量周围有名称空间:

<anyType xmlns:q1="http://www.w3.org/2001/XMLSchema"
         d3p1:type="q1:int"
         xmlns:d3p1="http://www.w3.org/2001/XMLSchema-instance">
  3
</anyType> 

3.
我的问题是:是否有必要使用namesapce进行反序列化,如果没有,如何消除它们?我如何告诉它字段是整数,这样它就不会输入“anytype”

谢谢,
Brian

不,这些名称空间不会减慢反序列化的速度。这些URI不是serialiser访问的Web端点:它们只是标识符——碰巧使用Web URI方案以保证唯一性的标签。你可以把它们安全地留在里面。

顺便说一句。。如果确实需要去掉默认名称空间,请执行以下操作:

        XmlSerializer x = new XmlSerializer(msg.GetType());

        StringWriter sw = new StringWriter();

        var namespaces = new XmlSerializerNamespaces();
        namespaces.Add("", "");

        x.Serialize(sw, msg, namespaces);

        string s = sw.ToString();
        sw.Close();

承认我刚从你的回答中学到了一些新东西有多尴尬?我一直想知道那些名称空间。@MusiGenesis,关于你的查询,这一点都不令人尴尬。谢谢,我想知道为什么这么多人要花这么多精力来删除它们。我遇到过一次不得不删除名称空间的情况。由于某种原因,他们导致我使用的第三方库崩溃。我一直没有弄清原因,因为未来的版本解决了这个问题。如果您使用的是SQL Server 2005或更高版本,那么应该使用XML列。