How can I get position in the original xml file of an xml tag after deserialization into a .NET object using XmlSerializer ?
Here is an example XML
Another, more simple approach: Let the deserializer do the work.
Add LineInfo and LinePosition properties to all classes for which you would like to have position information:
[XmlRoot("Root")]
public class AddressDetails
{
[XmlAttribute]
public int LineNumber { get; set; }
[XmlAttribute]
public int LinePosition { get; set; }
...
}
This of course can be done by subclassing.
Load an XDocument with LoadOptions.SetLineInfo.
Add LineInfo and LinePosition attributes to all elements:
foreach (var element in xdoc.Descendants())
{
var li = (IXmlLineInfo) element;
element.SetAttributeValue("LineNumber", li.LineNumber);
element.SetAttributeValue("LinePosition", li.LinePosition);
}
Deserializing will populate LineInfo and LinePosition.
Cons: