tags:

views:

51

answers:

3

Hi there,

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

A: 

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;
Eugene Cheverda
Is this my only option? I have no need for a Server object in my code. Is there no way of telling the serializer to ignore that tag?
Bob
I'm afraid that not...
Eugene Cheverda
@Bob: You can step over the Server tag by reading the document and getting its child nodes:XmlDocument doc = new XmlDocument();doc.Load(xmlFilePath);Console.WriteLine( doc.ChildNodes[1].InnerXml); // child 0 is <? xml...
jmservera
You can remove `Server` tag from xml at runtime while opening/reading xml file if you don't want to create `Server` class in code.
Eugene Cheverda
A: 

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

Ramesh Vel
Thanks. So that's my only option? I have to deserialize the Server object ... there's no way of telling the serializer to ignore this element?
Bob
+1  A: 

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());
prostynick