Search code examples
c#xmldatamember

Can I get DataMember names in the code?


in one project, I use datamember to serialize a class to an xml file, like,

[DataMember]
public string Member1;

later I query the xml to get one value out, like:

XmlNode1.SelectSingleNode("Member1");

Is it possible that make the Member1 above to a variable so when I change the DataMember name to be Member2 the Member1 in the query can be changed to Member2 automatically ,rather than I manually change it?


Solution

  • I am not exactly sure I understand what you hope to achieve, but I am thinking if you want to be able to centrally control the output from the serialization, you could define the tag in say a public static class.

    static class SerializationConstants
    {
      public static string MemberTag = "Member1"; //or "Member2"
    }
    

    Then in your datamember you can use the property with the Name attribute.

    [DataMember(Name=SerializationConstants.MemberTag)
    public string Member1;
    

    That would control serialization such that in your code for querying the xml, you can do something like:

    XmlNode1.SelectSingleNode(SerializationConstants.MemberTag)
    

    It would be a hack but I guess it should do if I understood your question correctly.