【发布时间】:2013-10-22 07:53:06
【问题描述】:
我有一个完整的构建对象列表,我想将它序列化为一个 XML 文件。基本序列化工作正常,但将值转换为属性以获得更好的可读性却奇怪地失败了,除了 int 值。
这是我正在使用的应该序列化的建筑类:
public class building
{
[XmlAttribute]
public string strName { set; get; } //name
[XmlAttribute]
public int intCount { set; get; } //count of building
[XmlAttribute]
public int intCost { set; get; } //running cost of building
[XmlAttribute]
public string strProd { set; get; } //product
[XmlAttribute)]
public string strRes1 { set; get; } //first ressource required
[XmlAttribute]
public string strRes2 { set; get; } //second ressource required
[XmlAttribute]
public int intTime { set; get; } //time to build in seconds
}
如果我省略 [XMLAttribute] 标签,XML 文件输出如下:
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfBuilding xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<building>
<strName>Holzfäller</strName>
<strKind>Produktion</strKind>
<intCost>2</intCost>
<strProd>Holz</strProd>
<strRes1 />
<strRes2 />
<intTime>105</intTime>
</building>
正如所说的那样很好,只是很难获得文件中超过 50 座建筑物的概览。使用上述代码创建的 XML 文件如下所示:
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfBuilding xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<building intCount="0" intCost="0" intTime="0" />
<building intCount="0" intCost="0" intTime="0" />
如您所见,仅添加了 int 值,甚至这些值也是 FALSE。所有值都设置为零。奇怪的是,如果我在创建列表后更新程序中的一个值,那么更改也会反映在 XML 中。只是基本值似乎被忽略/更改为零。
编辑:我也尝试像这样设置 DataType:
[XmlAttribute(DataType = "string")]
但这也只会使字符串变得噗噗而根本不显示。
有点迷失了这一点。如果我只是将 Attribute 的东西排除在外,那么一切都可以正常工作,所以我至少可以确定我的其余代码不会引起任何问题。但是为什么 XMLSerializer 会忽略作为字符串的对象属性并重置所有 int 值呢?我该如何改变?
很抱歉,如果其他地方有人问过这个问题,我找不到合适的词来让谷歌解决我的问题。主要是因为我不明白这里发生了什么,也不知道从哪里开始。我找到的文档只是显示了我在做什么,声称它会起作用。但这并不明显:-(
【问题讨论】:
-
尝试指定属性like here的类型。
-
已经尝试过了,字符串仍然会消失。我忘了说,对不起。编辑了我的帖子以反映这一点。
-
如果您想在很大程度上提高可读性,您应该从属性中删除类型前缀并将类型信息存储在模式中。