gpt4 book ai didi

c# - XML 将空属性反序列化为零和假

转载 作者:太空宇宙 更新时间:2023-11-03 11:13:47 25 4
gpt4 key购买 nike

我正在将缺少某些属性的 xml 文档传递给反序列化器。我需要结果对象中的缺失值为 null,但目前 ints 反序列化为零,bools 为 false。

下面的示例显示了一个正确反序列化了 vals 的文档,但是没有 vals 的文档返回了零和空值。

如何强制反序列化器不这样处理缺失的属性。

using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace SOQuestion
{
class Program
{
static void Main(string[] args)
{

var resultWithVals = getObject(docWithVals());
var resultWithoutVals = getObject(docWithoutVals());

Console.WriteLine("WITH VALS");
Console.WriteLine(resultWithVals.someBool);
Console.WriteLine(resultWithVals.someFloat);
Console.WriteLine(resultWithVals.someInt);
Console.WriteLine(resultWithVals.someString);


Console.WriteLine("WITHOUT VALS"); // nulls are returned here as zero and false
Console.WriteLine(resultWithoutVals.someBool);
Console.WriteLine(resultWithoutVals.someFloat);
Console.WriteLine(resultWithoutVals.someInt);
Console.WriteLine(resultWithoutVals.someString);

Console.ReadLine();


}

public static XmlDocument docWithVals()
{
var doc = new XmlDocument();
var el = (XmlElement)doc.AppendChild(doc.CreateElement("Result"));
el.SetAttribute("someString", "Hello World");
el.SetAttribute("someBool", "true");
el.SetAttribute("someInt", "1");
el.SetAttribute("someFloat", "1.1");
return doc;

}

public static XmlDocument docWithoutVals()
{
var doc = new XmlDocument();
var el = (XmlElement)doc.AppendChild(doc.CreateElement("Result"));
el.SetAttribute("someString", "Hello World");
return doc;

}


public static Result getObject(XmlDocument doc)
{

var mySerializer = new XmlSerializer(new Result().GetType());
var myStream = new MemoryStream();
doc.Save(myStream);
myStream.Position = 0;
var r = mySerializer.Deserialize(myStream);
return (Result)r;
}

}

[Serializable]
public class Result
{
[XmlAttribute]
public string someString { get; set; }
[XmlAttribute]
public bool someBool { get; set; }
[XmlAttribute]
public int someInt { get; set; }
[XmlAttribute]
public float someFloat { get; set; }

}

}

最佳答案

您可以使用 DefaultValueAttribute 为未初始化的字段提供默认值。在你的情况下你可以写

using System.ComponentModel;
using System.Configuration;

[XmlAttribute, DefaultValue(true)]
public bool someBool { get; set; }

编辑。请参阅 MSND 页面上的说明 note on MSDN :

A DefaultValueAttribute will not cause a member to be automatically initialized with the attribute's value. You must set the initial value in your code.

此问题也已在 XML serialization and DefaultValue("") related problem in c# 中解决. 因此,要设置默认值,您必须在代码中指定这些值。


希望对您有所帮助。

关于c# - XML 将空属性反序列化为零和假,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13251548/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com