views:

124

answers:

3

I have the following XML snippet:

<dmFiles>
−
<dmFile dmUpFileGuid="" dmFileDescr="testcase01.pdf" dmFileMetaType="main" dmFileGuid="" dmMimeType="pdf" dmFormat="">

If I create a strongly typed C# class with string properties for the dmFile attributes (eg: dmFileDescr), how can I ensure these attributes will serialize to properties in my c# class?

+1  A: 

By using Xml attributes on your class member. Use [XmlAttribute("name")]. Your implementation would look like this:

[XmlRoot("dmFile")]
public class DmFile
{
   [XmlAttribute("dmUpFileGuid")]
   public String UpFileGuid { get;set; }

   ...
}
jdehaan
A: 

You can (de)serialize from/to XML with the XmlSerializer and marking up the target class with Attributes provided for Xml-Serialization.

Mark your public properties with the correct attribute. It should be XmlAttributeAttribute. The enclosing class must map on the dmFile-Element (XmlRootAttribute) If the property is called differently, or the class is called differently than the XML element, you need to specify the XML-Element/Attribute name.

flq
A: 

Try this:

[Serializable]
[XmlRoot(ElementName="dmFile")]
public class File
{
    [XmlAttribute(AttributeName="dmUpFileGuid")]
    public string UploadGuid { get; set; }
    [XmlAttribute(AttributeName = "dmFileDescr")]
    public string Description { get; set; }
    [XmlAttribute(AttributeName = "dmFileMetaType")]
    public string MetaType { get; set; }
    [XmlAttribute(AttributeName = "dmFileGuid")]
    public string FileGuid { get; set; }
    [XmlAttribute(AttributeName = "dmMimeType")]
    public string MimeType { get; set; }
    [XmlAttribute(AttributeName = "dmFormat")]
    public string Format { get; set; }
}

And deserialize your XML as follow:

XmlSerializer s = new XmlSerializer(typeof(File));
File file = s.Deserialize(new StringReader(@"<dmFile ... />")) as File;
Rubens Farias