I have an XML dox like this:
<?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));
where Database is a Class with a collection of Devices.
It works fine when I comment out the Server tags in the XML file but i don't want to. I get an error saying "There is an error in XMl document line (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?
I tried putting [XmlRootAttribute("Database")] on the Database object but I still get the same error
If you really don't want to create Server
class just remove <Server/>
"wrapper" from loaded xml.
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:
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
[Serializable]
[XmlRootAttribute("Server", Namespace = "", IsNullable = false)]
public class YourClass
{
public YourClass()
{
}
[XmlAttribute]
public string Manufacturer { get; set; }
....
}
and deserialize the server not database
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.