如何将一个类序列化为字段 [英] How to serialize a class as field
问题描述
示例:
public class MYELEMENT
{
public string value;
}
上面将产生类似以下内容:
The above would produce something like the following:
<MYELEMENT><value>string</value></MYELEMENT>
就我的目的而言,我需要以下内容:
For my purposes I need the following:
<MYELEMENT>string</MYELEMENT>
我正在创建一个元素数组,该数组保留从外部源序列化的原始元素的顺序.
I am creating an array of elements that preserves the order of the original elements serialized from an external source.
public class MYROOT
{
[XmlElement(typeof(MYELEMENT1))]
[XmlElement(typeof(MYELEMENT2))]
[XmlElement(typeof(MYELEMENT3))]
public object[] nodes { get; set; }
}
每种类型可能有一个或多个元素,可以以任何顺序出现.因此,每个元素都表示为一个类对象.
所编写的代码可以正常工作,只不过反序列化此代码
There may be one or more elements of each type that can appear any order. Therefore, each element is represented as a class object.
The code, as written, works fine except that Deserializing this
<MYELEMENT>1</MYELEMENT>
序列化时会产生以下内容
produces the following when Serializing it out
<MYELEMENT />
目前正确,因为没有子元素.
是否可以使用XML属性或其他方法来产生所需的内容?
这样的东西
Which is correct at the moment, because there is no sub-element.
Is there an XML attribute or other method that can be applied to produce what I need?
Something like this
public class MYELEMENT
{
[this is the elements value]
public string value;
}
或这个
or this
[this is a wrapper for the real element]
public class Foo
{
public string MYELEMENT { get; set; }
}
Thanks!
推荐答案
解决方案是使用[XmlText()]
以获得正确的结果.
示例:
The solution is to use[XmlText()]
for correct results.
Example:
public class MYELEMENT1
{
[XmlText()]
public string value;
}
public class MYELEMENT2
{
[XmlText(typeof(int))]
public int value;
}
序列化的结果:
Result of Serializing :
<MYELEMENT1>string</MYELEMENT1>
<MYELEMENT2>1</MYELEMENT2>
我建议避免在此级别上进行手动"序列化,并使用 Data Contracts .
这种方法是最非侵入性的,最容易实现,同时最灵活.
请参阅: http://msdn.microsoft.com/en-us/library/ms733127.aspx [ ^ ].
请在我倡导这种方法的地方查看我过去的答案:
如何在我的表单应用程序? [ ^ ],
创建属性文件... [反序列化json字符串数组 [
I would recommend to avoid "manual" serialization on this level and use Data Contracts.
This approach is most non-intrusive, easiest to implement and most flexible at the same time.
Please see: http://msdn.microsoft.com/en-us/library/ms733127.aspx[^].
Please also see my past answers where I advocate this approach:
How can I utilize XML File streamwriter and reader in my form application?[^],
Creating property files...[^],
deseralize a json string array[^].
这篇关于如何将一个类序列化为字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!