Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object position (line, column) in XML after deserialization .NET

Tags:

c#

.net

xml

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); 
like image 276
honzajscz Avatar asked Mar 04 '14 13:03

honzajscz


1 Answers

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:

  • Line information only for elements that are deserialized as class, not for simple elements, not for attributes.
  • Need to add attributes to all classes.
like image 95
Martin Avatar answered Oct 21 '22 04:10

Martin