类声明之前的 C# XML 序列化属性
我有这个类
public class dtoObject : CommonBase
{
[XmlArray("SomeItems"), XmlArrayItem("SomeItem")]
public List<dtoSomeItem> SomeItems
{
get { return _SomeItems; }
set { _SomeItems = value; }
}
}
,我想使用 XML 序列化来使 XML 字符串看起来像:
<Objects>
<Object>
<SomeItems>
<SomeItem>
1
</SomeItem>
<SomeItem>
2
</SomeItem>
</SomeItems>
</Object>
<Object>
<SomeItems>
<SomeItem>
3
</SomeItem>
<SomeItem>
4
</SomeItem>
</SomeItems>
</Object>
</Objects>
但对于我来说,我无法弄清楚
public class dtoObject
在属性方面要放在前面什么,这样
<Objects><Object>...</Object><Object>...
当我序列化它时我就得到了。
有什么想法吗?
I have this class
public class dtoObject : CommonBase
{
[XmlArray("SomeItems"), XmlArrayItem("SomeItem")]
public List<dtoSomeItem> SomeItems
{
get { return _SomeItems; }
set { _SomeItems = value; }
}
}
and I would would like to use XML Serialization to make the XML string appear to be:
<Objects>
<Object>
<SomeItems>
<SomeItem>
1
</SomeItem>
<SomeItem>
2
</SomeItem>
</SomeItems>
</Object>
<Object>
<SomeItems>
<SomeItem>
3
</SomeItem>
<SomeItem>
4
</SomeItem>
</SomeItems>
</Object>
</Objects>
But for the life of me I cant figure out what to put before
public class dtoObject
in terms of Attributes, so that I get
<Objects><Object>...</Object><Object>...
when I serialize this.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为您不能使用对象结构来执行此操作,因为 XML 有效地声明了 SomeItems 集合的包装器。例如:
I don't think that you can do this with your object structure because the XML effectively declares a wrapper around the SomeItems collection. For example:
这就是我要做的工作。感谢 comptent_tech 和 dthorpe 的帮助。我像这样创建了 DTO:
我执行序列化的函数是这样的:
这样做会创建以下 xml 格式:
Here is what I got to work. Thanks to comptent_tech and dthorpe for their help. I created my DTO like so:
My function that does the serializing is this:
Doing this creates the xml format of:
您需要在类声明前面添加类似
XmlRootAttribute("Object", Namespace="", IsNullable=false)
的内容。这告诉 XML 序列化程序使用至于
标记,除非您序列化 dtoObject 数组,否则您不会得到它。这超出了 dtoObject 类型的范围。You'll need something like
XmlRootAttribute("Object", Namespace="", IsNullable=false)
in front of the class declaration. That tells the XML serializer to use the<Object>
tag to represent the dtoObject in the XML text.As for the
<Objects>
tag, you won't get that unless you are serializing an array of dtoObject. That is beyond the scope of the dtoObject type.