0

I have an xml which looks like this

   <Planets> 
   <Planet> 
    <Name Units="days" Order="1">
     <Lists>
      <List Units="nights">list_ends_here</List>
     </Lists>
   </Name>
  </Planet>
  </Planets>    

If Units attribute has different values like shown here, The code has an error. I am getting the error, but I wanted to report the line number where the error occurs. I have different xmls where Units has different values so line numbers are different.

The code where I load the xml document

   XDocument xdoc = XDocument.Load(file, LoadOptions.SetLineInfo);
IEnumerable<XElement> planets = xdoc.Root.Descendants("Name");
foreach (XElement category in categories)
{
    //get line number for element 
    string lineNumber = ((IXmlLineInfo)category).HasLineInfo() ? ((IXmlLineInfo)category).LineNumber : -1;
}

The way I parse these from the xml:

foreach(XElement pl_name in planets)
        {
          string Units = pl_name.Attribute("Units").Value;
          string units_on_list = pl_name.Descendants("Lists").Elements("List").Select(x => (string)x.Attribute("Units")).ToList()
        }

LoadOptions.SetLineInfo is not giving me the line number

Sean Davis
  • 23
  • 1
  • 6
  • [`IXmlLineInfo`](https://learn.microsoft.com/en-us/dotnet/api/system.xml.ixmllineinfo?view=net-7.0) reports the line number **in the XML file** at which the element was loaded. And in fact it seems to work. Your code where you "load the xml document" doesn't compile because `categories` is undefined, but if I change it to `planets` then the line number is reported correctly, see https://dotnetfiddle.net/hFJQKF. See [C# how can I debug a deserialization exception?](https://stackoverflow.com/a/29882953/3744182) for details on interpreting the values from `IXmlLineInfo`. – dbc Nov 11 '22 at 23:34
  • Does that answer your question? If not, could you please [edit] your question and explain a little what you are trying to do, ideally with a [mcve] that can be compiled and demonstrates the problem? – dbc Nov 11 '22 at 23:35

0 Answers0