shrimp rice
shrimp rice

Reputation: 322

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?

Upvotes: 0

Views: 1732

Answers (3)

John Gathogo
John Gathogo

Reputation: 4655

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.

Upvotes: 1

Ryan Bennett
Ryan Bennett

Reputation: 3432

This doesn't sound like a great idea.

If you are concerned about property names changing in your class with the DataMember attribute, you are probably going to want a layer of abstraction in the form of a DTO between that class and your XML querying. That way your XML querying class doesn't care if that member name changes or not because your DTO will never change. Just the mapping from the DTO to the volitle class.

Upvotes: 0

mellamokb
mellamokb

Reputation: 56769

You should deserialize the XML file when working with it, then you can use field names to access properties and they would change if you would do refactoring.

Upvotes: 0

Related Questions