luisvelalopez
luisvelalopez

Reputation: 11

Serialize complex xml file c#

I would like to serialize the following xml file:

<?xml version="1.0" encoding="utf-8"?>
<CrossReference>
<Object Name="Sensor01;">
<Location Name="Sensor01.GEN">
      <Member Name="GEN" Datatype="Sensor_Gen">
        <Comment xmlns="http://www.siemens.com/automation/Openness/SW/Interface/v5">
          <MultiLanguageText Lang="en-US">Pressure sensor 01</MultiLanguageText>
          <MultiLanguageText Lang="de-DE">Drucksensor 01</MultiLanguageText>
        </Comment>
      </Member>
</Location>
</Object>
</CrossReference>

I defined the Class as follows:

using System;
using System.Xml.Serialization;

namespace Configurator.Models.XmlFile
{
    [Serializable]
    public class CrossReference
    {
        [XmlElement]
        public Object[] Object { get; set; }
    }
    public class Object
    {
        [XmlAttribute]
        public string Name { get; set; }
        [XmlElement]
        public Location[] Location { get; set; }
    }

    public class Location
    {
        [XmlAttribute]
        public string Name { get; set; }
        [XmlElement]
        public Member[] Member { get; set; }
    }

    public class Member
    {
        [XmlAttribute]
        public string Name { get; set; }
        [XmlAttribute]
        public string Datatype { get; set; }
        [XmlElement(Namespace = @"http://www.siemens.com/automation/Openness/SW/Interface/v5")]
        public Comment Comment { get; set; }
    }

    public class Comment
    {
        [XmlElement]
        public MultiLanguageText[] MultiLanguageText { get; set; }
    }

    public class MultiLanguageText
    {
        [XmlAttribute]
        public string Lang { get; set; }
        [XmlElement("MultiLanguageText")]
        public string Text { get; set; }
    }
}

I works almost completely. Just the part cannot be serialized:

<MultiLanguageText Lang="en-US">Pressure sensor 01</MultiLanguageText>
<MultiLanguageText Lang="de-DE">Drucksensor 01</MultiLanguageText>

The attribute Lang can be serialized but the content of the MultiLanguageText tag not. The public property "Text" of the class MultiLanguageText is allways interpreted as null.

Any suggestion?

Upvotes: 1

Views: 72

Answers (1)

Xerillio
Xerillio

Reputation: 5261

You should use the [XmlText] attribute:

public class MultiLanguageText
{
    [XmlAttribute]
    public string Lang { get; set; }

    // Not: [XmlElement("MultiLanguageText")]
    [XmlText]
    public string Text { get; set; }
}

See this example fiddle.

Upvotes: 1

Related Questions