gpt4 book ai didi

c# - 没有命名空间的 XML 反序列化

转载 作者:数据小太阳 更新时间:2023-10-29 02:36:38 25 4
gpt4 key购买 nike

我在反序列化没有命名空间的 XML 时遇到了一些麻烦。奇怪的是,我收到一个异常消息“XML 文档 (2,2) 中存在错误。”;内部异常“command_strings xmlns = 不是预期的。”。我在 VS2008 中编码。

我的 XML

<?xml version="1.0" encoding="utf-8"?>
<command_strings version="1">
<commands>
<command cmd_id="1" state_id="1" label="On" cmd_type="F" cmd_string="1" />
</commands>
</command_strings>

我的类(class)

public class Command
{
[System.Xml.Serialization.XmlAttribute("cmd_id")]
public int cmd_id { get; set; }

[System.Xml.Serialization.XmlAttribute("state_id")]
public int state_id { get; set; }

[System.Xml.Serialization.XmlAttribute("label")]
public string label { get; set; }

[System.Xml.Serialization.XmlAttribute("cmd_type")]
public string cmd_type { get; set; }

[System.Xml.Serialization.XmlAttribute("cmd_string")]
public string cmd_string { get; set; }
}

[System.Xml.Serialization.XmlRoot("commands_strings")]
public class CommandCollection
{
[System.Xml.Serialization.XmlAttribute("version")]
public int version { get; set; }

[XmlArray("commands")]
[XmlArrayItem("command", typeof(Command))]
public Command[] Command { get; set; }
}

public bool IsValidXML()
{
CommandCollection commandscollection = null;
XmlSerializer dserial = new XmlSerializer(typeof(CommandCollection));

using (StreamReader streamReader = new StreamReader(@"C:\123.xml"))
{
commandscollection = (CommandCollection)dserial.Deserialize(streamReader);
streamReader.Close();
}
}

最佳答案

试试这个反序列化。

Stream Read = null;
object m_Configuration = null;
try
{
FileInfo FI = new FileInfo("C:\\");

Read = FI.OpenRead();
XmlSerializer serializer = new XmlSerializer(typeof(CommandCollection));

m_Configuration = serializer.Deserialize(Read);

}
finally
{
if (Read != null)
{
Read.Close();
}
}

您也可以尝试不将 Root 属性放在 CommandCollection 之上,而是使用

[XmlType("commands_strings")]

关于c# - 没有命名空间的 XML 反序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11874187/

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