简体   繁体   English

C#XML序列化错误

[英]C# XML serialization error

I have an XML dox like this: 我有一个XML dox,如下所示:

<?xml version="1.0" encoding="utf-8"?>
<Server Manufacturer="SQL" Version="1">
  <Database Name="Test123" >
    <Devices>
      <Device Name="Testdata" ..../>
      <Device Name="Testlog" ..../>
    </Devices>
  </Database>
</Server>

I want to deserialize it like this: var database = (Database)xmlSerializer.Deserialize(new StreamReader(xmlFilePath)); 我想像这样反序列化:var database =(Database)xmlSerializer.Deserialize(new StreamReader(xmlFilePath));

where Database is a Class with a collection of Devices. 其中Database是带有设备集合的类。

It works fine when I comment out the Server tags in the XML file but i don't want to. 当我注释掉XML文件中的Server标记但我不想这么做时,它工作正常。 I get an error saying "There is an error in XMl document line (1, 4)" 我收到一条错误消息:“ XMl文档行(1、4)中存在错误”

How can I tell the serialize to ignore the server tag and do I need to put a namespace in the XML file? 如何告诉序列化忽略服务器标签,是否需要在XML文件中放置名称空间?

I tried putting [XmlRootAttribute("Database")] on the Database object but I still get the same error 我尝试将[XmlRootAttribute(“ Database”)]放在数据库对象上,但仍然出现相同的错误

If you really don't want to create Server class just remove <Server/> "wrapper" from loaded xml. 如果您真的不想创建Server类,则从加载的xml中删除<Server/> “ wrapper”。

For example, instead of this: 例如,代替此:

(Database)xmlSerializer.Deserialize(
    new StreamReader(xmlFilePath));

do this: 做这个:

(Database)xmlSerializer.Deserialize(
    XElement.Load(xmlFilePath).Element("Database").CreateReader());

You should deserialize Server class which will look like: 您应该反序列化Server类,如下所示:

public class Server
{
    public string Manufacturer{get;set;}
    public int Version {get;set;}
    public Database Database {get;set;}
}

Then deserialize: 然后反序列化:

var server = (Server)xmlSerializer.Deserialize(new StreamReader(xmlFilePath));
var database = server.Database;

I believe your XmlRootAttribute is the problem, add Server as XmlRootAttribute .. below the sample code 我相信您的XmlRootAttribute是问题,请在示例代码下方将Server添加为XmlRootAttribute ..

[Serializable]
[XmlRootAttribute("Server", Namespace = "", IsNullable = false)]    
public class YourClass
{
    public YourClass()
    {

    }
    [XmlAttribute]
    public string Manufacturer { get; set; }
   ....

}

and deserialize the server not database 并反序列化服务器而不是数据库

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM