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

前端 未结 2 597
我寻月下人不归
我寻月下人不归 2020-12-17 02:54

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

          


        
2条回答
  •  佛祖请我去吃肉
    2020-12-17 03:15

    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.

提交回复
热议问题