0
votes

I'm currently working on a .NET 4.6 console application. I try to parse/serialize a XML from a file.

Currently I'm struggling with the serialization of a Complex Type in XML.

Given is the following XML element:

<cool_element>
   <master visible="true">A1</master>
</cool_element>

as well as it's according XSD specification:

<xs:element name="cool_element">
   <xs:complexType>
      <xs:sequence>
         <xs:element name="master">
            <xs:complexType>
               <xs:simpleContent>
                  <xs:extension base="xs:string">
                     <xs:attribute type="xs:string" name="visible"/>
                 </xs:extension>
              </xs:simpleContent>
            </xs:complexType>
         </xs:element>
      </xs:sequence>
   </xs:complexType>
</xs:element>

My serialization class in C# looks like this:

[XmlRoot(ElementName = "cool_element")]
public class CoolElement
{
    [XmlElement("master")]
    public string Master { get; set; }
}

This works fine to retrieve the string value. But I don't know how to get the attribute visible from my master element.

Do you have an idea on how to solve this?

Thank you!

1

1 Answers

1
votes

master should be it's own object class, I would solve it this way (note the xml attributes for value and visible):

[XmlRoot(ElementName = "cool_element")]
public class CoolElement
{
    private Master masterField;
    public Master master { get { return this.masterField; } set { this.masterField = value; } }
}

[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public class Master
{
    private bool visibleField; 

    private string valueField;

    [System.Xml.Serialization.XmlAttributeAttribute()]
    public bool visible { get { return this.visibleField; } set { this.visibleField = value; } }

    [System.Xml.Serialization.XmlTextAttribute()]
    public string Value { get { return this.valueField; } set { this.valueField = value; } }
}

then to read the data:

        CoolElement cool = null;
        string path = @"yourxmlfilename.xml";
        XmlSerializer serializer = new XmlSerializer(typeof(CoolElement));
        using (var reader = XmlReader.Create(path))
        {
            cool = (CoolElement)serializer.Deserialize(reader);
            Console.WriteLine("master value: " + cool.master.Value);
            Console.WriteLine("attribute visible value: " + cool.master.visible);
        }

does that help you?