我有一个完整的构建对象列表,我想将其序列化为 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。所有值均设置为零。奇怪的是,如果我在创建列表后更新程序中的一个值,则更改也会反射(reflect)在 XML 中。只是基值似乎被忽略/更改为零。
编辑:我也尝试像这样设置数据类型:
[XmlAttribute(DataType = "string")]
但这也只会让字符串变得糟糕并且根本不显示。
在这一点上有点失败。如果我只保留属性内容,一切都工作正常,所以我至少确定我的代码的其余部分不会引起任何问题。但是为什么 XMLSerializer 会忽略字符串对象属性并重置所有 int 值呢?我该如何改变这个?
抱歉,如果其他地方有人问过这个问题,我无法找到合适的词让谷歌来解决我的问题。主要是因为我不明白这里发生了什么,也不知道从哪里开始。我发现的文档只是显示了我正在做的事情,并声称它会起作用。但它并不明显:-(
最佳答案
您的字符串
为空,因此它们不是通过序列化写入的。
在 building
的默认构造函数中将字符串字段初始化为 string.Empty
,它们将出现在输出中。
我在构建
中使用此构造函数测试了它:
public building()
{
strProd = "";
}
输出:
<?xml version="1.0" encoding="utf-16"?>
<ArrayOfBuilding xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<building intCount="0" intCost="0" strProd="" intTime="0" />
<building intCount="0" intCost="0" strProd="" intTime="0" />
</ArrayOfBuilding>
为什么行为的属性不同?
Xml 能够通过省略内容来显示元素中可为空的类型。但是,属性无法显示可空值和以区别于空字符串。因此,该属性被完全省略。
关于C# XmL 序列化 - 将项目设置为属性仅显示 XML 中的整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19512109/