I wants to set a xml document as a property, where user can set the values of xml attributes and tags but can not change the xml formate. user will not be allowed to delete or add any node in that xml.
Can any body help me out of this ?
Loading
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Blackbarbie Bb56 reputationPosted Sep 2, 2015, 4:16 AM EDT
There are a couple of ways of doing this. If the data contained in the xml document can be translated into a serializable class (default constructor, getters and setters for all properties - since the data is xml anyway, it's probably trivially serializable) , you can simply expose the document like this:
[Serializable] public class MyDocument { [XmlElement(IsNullable = False)] public int Property1 { get; set } [XmlArray(IsNullable= False)] public List Property2 { get; set; } }This allows you to use the XmlSerializer class to load and save documents to disk, IO streams etc. without having to directly interact with the Xml DOM. Setting IsNullable to false means that when serialization takes place, a node will always be generated, or an exception thrown.
Otherwise, you can create a wrapper around the document, like so:
public class MyDocument { private XDocument the_document = null; public string Property1 { get { return this.the_document... //getter DOM manipulation here } set { if(value == null) throw new ArgumentNullException(nameof(value)); this.the_document... = value //setter DOM manipulation here } } }Either way, your aim is to hide the flexibility of the XML document from the user, and use an accessor class you have written to manipulate the elements you want to change.
If the document has an xsd, your task can be even easier - xsd.exe will allow you to automatically generate Seralizable C# classes from a given xsd schema