0

I have an XML document I'm trying to deseralize that has a attribute that is ref which in C# can not be used to declare a variable hence the below doesn't work

 [XmlAttribute()]
 public string ref;

Anyway to get this to deseralize properly? I know it is case sensitive so Ref wouldn't work.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
AmericanSuave
  • 363
  • 3
  • 4
  • 14
  • Possible duplicate of [How do I use a C# keyword as a property on an anonymous object?](http://stackoverflow.com/questions/421257/how-do-i-use-a-c-sharp-keyword-as-a-property-on-an-anonymous-object) – T.S. Oct 07 '15 at 22:20

2 Answers2

2

You can provide a name in the attribute:

[XmlAttribute("ref")]
public string anynameyouwant;
snow_FFFFFF
  • 3,235
  • 17
  • 29
0

You can change the attribute name in the xml file, by using the AttributeName, such as in the following example:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace soans
{

    public class Test
    {

        //problematic attribute (ref is reserved)
         [XmlAttribute(AttributeName="ref")]
         public string RefAttr {get;set;}


         //other attributes as well
         [XmlAttribute()]
         public string Field { get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            string filename = ""; //use your path here

            Test original = new Test()
            {
                RefAttr = "ref",
                Field = "test"
            };
            //serialiser
            XmlSerializer ser = new XmlSerializer(typeof(Test));

            //save to file
            TextWriter writer = new StreamWriter(filename);
            ser.Serialize(writer, original);
            writer.Close();

            //read from file
            TextReader reader = new StreamReader(filename);
            var fromfile = ser.Deserialize(reader) as Test;
            if(fromfile!=null)
            {
                Console.WriteLine(fromfile.RefAttr);

            }
            reader.Close();
            Console.ReadKey();

        }
    }
}
ziaziosk
  • 136
  • 4