[C#] XmlElement op root node

Pagina: 1
Acties:

Acties:
  • 0 Henk 'm!

  • Mephix
  • Registratie: Augustus 2001
  • Laatst online: 15-03 08:21
Ik heb een XML file waarin alle elementen en attributen in lowercase staan:

XML:
1
2
3
4
<?xml version="1.0" encoding="UTF-8"?>
<klant>
    <adres straat="Stationslaan" huisnummer="10">
</klant>


De classes in c# zijn camel-cased en daarom gebruik ik XmlElement en XmlAttribute om de juiste vertaling te maken van XML naar classname voor deserialisatie:

C#:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public class Klant
{
    private Adres _Adres;

    [XmlElement("adres")]
    public Adres Adres
    {
        get { return _Adres; }
        set { _Adres = value; }
    }
}

public class Adres
{
    private string _Straat;
    private string _Huisnummer;

    [XmlAttribute("straat")]
    public string Straat
    {
        get { return _Straat; }
        set { _Straat = value; }
    }

    [XmlAttribute("huisnummer")]
    public string Huisnummer
    {
        get { return _Huisnummer; }
        set { _Huisnummer = value; }
    }
}


Dit werkt, behalve voor de root node "klant" in onderstaand voorbeeld:
C#:
1
2
3
4
5
public Klant DeserializeXml()
{
    XmlSerializer serializer = new XmlSerializer(typeof(Klant));
    return (Klant)serializer.Deserialize(new StringReader(xmldata));
}


Exception: There is an error in XML document
InnerException: <klant xmlns=''> was not expected.

Verander ik nu de naam van de class "Klant" naar "klant" dan gaat het wel goed, maar dat wil ik liever niet.

Hoe kan ik er voor zorgen dat het "klant" element uit de XML gedeserialiseerd wordt naar de "Klant" class in .NET ? Ik kan op class niveau niet de XmlElement attribute toevoegen:

C#:
1
2
3
4
5
[XmlElement("klant")]
public class Klant
{

}

[ Voor 13% gewijzigd door Mephix op 05-02-2009 11:33 ]


Acties:
  • 0 Henk 'm!

  • whoami
  • Registratie: December 2000
  • Laatst online: 21:57
Gebruik XmlRootAttribute ipv XmlElementAttribute op je Klant class.
(Het is nl. een root, en geen element).

[ Voor 9% gewijzigd door whoami op 05-02-2009 11:37 ]

https://fgheysels.github.io/


Acties:
  • 0 Henk 'm!

  • Mephix
  • Registratie: Augustus 2001
  • Laatst online: 15-03 08:21
C#:
1
2
3
4
5
[XmlRoot("klant")]
public class Klant
{

}


Werkt... tnx a lot!

Had niet gezocht op 'root' oid, alleen op XmlSerializer en Element, Attribute, dat soort keywords 8)7