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
<ArrayOfAddressDetails>
<AddressDetails>
<Number>4</Number>
<Street>ABC</Street>
<CityName>Bern</CityName>
</AddressDetails>
<AddressDetails>
<Number>3</Number>
<Street>ABCD</Street>
<CityName>Prague</CityName>
</AddressDetails>
</ArrayOfAddressDetails>
XMLto C# object mapping
[XmlRoot("Root")]
public class AddressDetails
{
[XmlElement("Number")]
public int HouseNo;
[XmlElement("Street")]
public string StreetName;
[XmlElement("CityName")]
public string City;
}
Desired result
XmlSerializer serializer = new XmlSerializer(typeof(List<AddressDetails>));
var list = serializer.Deserialize(@"C:Xml.txt") as List<AddressDetails>;
// this is what I would like to do
// getting information to origin of the property City of the 2nd object in the list
var position = XmlSerializerHelper.GetPosition(o => list[1].City, @"C:Xml.txt");
// should print "starts line=10, column=8"
Console.WriteLine("starts line={0}, column={1}", position.Start.Line, position.Start.Column);
// should print "ends line=10, column=35"
Console.WriteLine("ends line={0}, column={1}", position.End.Line, position.Start.Column);
// should print "type=XmlElement, name=CityName, value=Prague"
Console.WriteLine("xml info type={0}, name={1}, value={2}", position.Type, position.Name, position.Value);
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…