AmericanSuave
AmericanSuave

Reputation: 373

Identifier on XmlAttribute

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.

Upvotes: 0

Views: 194

Answers (2)

ziaziosk
ziaziosk

Reputation: 136

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();

        }
    }
}

Upvotes: 0

snow_FFFFFF
snow_FFFFFF

Reputation: 3311

You can provide a name in the attribute:

[XmlAttribute("ref")]
public string anynameyouwant;

Upvotes: 2

Related Questions