C#Serialize to XML - 有时会出现String属性? [英] C# Serialize to XML - String properties sometimes appear?
问题描述
我认为我在C#序列化理解中遗漏了一些东西。
我正在将一个C#类序列化为XML,以便通过Web服务进行传输。为简单起见,我有一个只有三个属性的类:
public partial class MyInfo:SerializableObject
{
private string ssnField;
private string suffixField;
private integer suffixIDField;
public MyInfo()
{
this .ssnField = string .Empty;
this .suffixField = string .Empty;
this .suffixIDField = 0 ;
}
public string SSN
{
获取 {返回 此。 ssnField; }
set {此 .ssnField = value 跨度>; }
}
public string 后缀
{
获取 {返回 此 .suffixField; }
set { this .suffixField = value 跨度>; }
}
public 整数SuffixID
{
get { return this .suffixIDField; }
set { this .suffixIDField = value 跨度>; }
}
}
这里是串行器的主旨:
使用(XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream,Encoding .UTF8){Formatting = Formatting.Indented})
{
xmlSerializer.Serialize(xmlTextWriter, this );
memoryStream =(MemoryStream)xmlTextWriter.BaseStream;
xmlText = new UTF8Encoding()。GetString(memoryStream.ToArray());
memoryStream.Dispose();
}
这里是我的输出:SSN或Suffix都没有设置超出string.empty调用。 SSN出现在XML中,后缀则没有出现。谁知道为什么?
< SSN / >
< 后缀ID > 0 < / SuffixID >
我不想传递空字段(如后缀)但我会解决知道为什么一个出现,一个不出现。
非常感谢。
我找到了回答!这是一个缺少的描述符:
[XmlElement(IsNullable = true)]
public string SSN
I think I''m missing something in my C# Serialization understanding.
I am serializing a C# class to XML to transfer across a web service. For simplicity''s sake, I have a class with only three properties:
public partial class MyInfo : SerializableObject
{
private string ssnField;
private string suffixField;
private integer suffixIDField;
public MyInfo()
{
this.ssnField = string.Empty;
this.suffixField = string.Empty;
this.suffixIDField = 0;
}
public string SSN
{
get { return this.ssnField; }
set { this.ssnField = value; }
}
public string Suffix
{
get { return this.suffixField; }
set { this.suffixField = value; }
}
public integer SuffixID
{
get { return this.suffixIDField; }
set { this.suffixIDField = value; }
}
}
And here''s the gist of the serializer:
using (XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8) { Formatting = Formatting.Indented })
{
xmlSerializer.Serialize(xmlTextWriter, this);
memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
xmlText = new UTF8Encoding().GetString(memoryStream.ToArray());
memoryStream.Dispose();
}
And here''s my output: Neither SSN or Suffix get set beyond the string.empty call. SSN shows up in the XML, Suffix does not. Anyone know why?
<SSN />
<SuffixID>0</SuffixID>
I''d prefer to not pass empty fields (like Suffix) but I''d settle to know why one appears, and one does not.
Thanks much.
I found the answer! It was an missing descriptor:
[XmlElement(IsNullable = true)] public string SSN
这篇关于C#Serialize to XML - 有时会出现String属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!