XmlAttribute上的标识符

时间:2015-10-07 20:18:41

标签: c# xml

我有一个XML文档,我试图去除deseralize,它有一个ref属性,在C#中不能用来声明一个变量因此下面没有工作

 [XmlAttribute()]
 public string ref;

无论如何要正确地解除这个问题?我知道它区分大小写,所以Ref不会工作。

2 个答案:

答案 0 :(得分:2)

您可以在属性中提供名称:

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

答案 1 :(得分:0)

您可以使用AttributeName更改xml文件中的属性名称,例如以下示例中所示:

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

        }
    }
}