gpt4 book ai didi

c# - 无法将 xml 反序列化为对象

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

我有以下代码,其中我正在尝试序列化和反序列化 StringResource 类的对象。请注意 Resource1.stringXml = 它来自资源文件。如果我通过 strelemet.outerXMl 我从 Deserialize 对象获取对象,但如果我通过 Resource1.stringXml 我得到以下异常

{“ 不是预期的。”} System.Exception {System.InvalidOperationException}

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

StringResource str = new StringResource();
str.DELETE = "CanDelete";
str.ID= "23342";
XmlElement strelemet = SerializeObjectToXmlNode (str);

StringResource strResourceObject = DeSerializeXmlNodeToObject<StringResource>(Resource1.stringXml);
Console.ReadLine();

}
public static T DeSerializeXmlNodeToObject<T>(string objectNodeOuterXml)
{
try
{
TextReader objStringsTextReader = new StringReader(objectNodeOuterXml);
XmlSerializer stringResourceSerializer = new XmlSerializer(typeof(T),string.Empty);
return (T)stringResourceSerializer.Deserialize(objStringsTextReader);
}
catch (Exception excep)
{
return default(T);
}
}

public static XmlElement SerializeObjectToXmlNode(object obj)
{
using (MemoryStream memoryStream = new MemoryStream())
{
try
{
XmlSerializerNamespaces xmlNameSpace = new XmlSerializerNamespaces();
xmlNameSpace.Add(string.Empty, string.Empty);
XmlWriterSettings writerSettings = new XmlWriterSettings();
writerSettings.CloseOutput = false;
writerSettings.Encoding = System.Text.Encoding.UTF8;
writerSettings.Indent = false;

writerSettings.OmitXmlDeclaration = true;

XmlWriter writer = XmlWriter.Create(memoryStream, writerSettings);

XmlSerializer xmlserializer = new XmlSerializer(obj.GetType());
xmlserializer.Serialize(writer, obj, xmlNameSpace);
writer.Close();
memoryStream.Position = 0;
XmlDocument serializeObjectDoc = new XmlDocument();
serializeObjectDoc.Load(memoryStream);

return serializeObjectDoc.DocumentElement;
}
catch (Exception excep)
{
return null;
}
}
}
}
public class StringResource
{
[XmlAttribute]
public string DELETE;
[XmlAttribute]
public string ID;
}

最佳答案

问题是您的 XML 根节点和您的类中的名称不匹配

< STRING ID="1" DELETE="True" />  -- STRING here
public class StringResource -- StringResource Here.

xmlroot 属性添加到您的类中,看看会发生什么

[XmlRoot( "STRING " )]
public class StringResource
{
[XmlAttribute]
public string DELETE;
[XmlAttribute]
public string ID;
}

关于c# - 无法将 xml 反序列化为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2491127/

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