Share via

XML - xDoc.XPathSelectElements

Markus Freitag 3,791 Reputation points
2021-07-16T07:44:32.593+00:00

Hello!

I am reading in the XML file and cannot cast to my list.
Why not.
With the var type it works. Then I have to copy everything again? What can be the cause? What is the solution?

<REASONS_STOP_BEFORE_TARGET>
    <REASON value="No Material"/>
    <REASON value="Changed operator"/>
    <REASON value="End of shift"/>
</REASONS_STOP_BEFORE_TARGET>

public class REASONS_STOP_BEFORE_TARGET : List<REASON>
{
 public REASONS_STOP_BEFORE_TARGET()
 {

 }

 //....
public class REASON
 {
 public string Value { set; get; }


 var result = (from e in xDoc.XPathSelectElements("//REASON")
   select new REASON
   {
   Value = e.Attribute("value").Value
   }).ToList();

// ** Works with var type  


// *** That works not, why?
REASONS_STOP_BEFORE_TARGET result = (from e in xDoc.XPathSelectElements("//REASON")
   select new REASON
   {
   Value = e.Attribute("value").Value
   }).ToList();

// ** Not work, why? Casting problem?
Developer technologies | C#
Developer technologies | C#

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.

0 comments No comments

Answer accepted by question author

Viorel 127K Reputation points
2021-07-16T08:10:07.59+00:00

If you decided to derive REASONS_STOP_BEFORE_TARGET from List and to use LINQ, then check this code:

public class REASONS_STOP_BEFORE_TARGET : List<REASON>
{
   public REASONS_STOP_BEFORE_TARGET( IEnumerable<REASON> collection ) : base( collection )
   {
   }
}

. . .

REASONS_STOP_BEFORE_TARGET result =
   new REASONS_STOP_BEFORE_TARGET( from e in xDoc.XPathSelectElements( "/*/REASON" )
                                   select new REASON
                                   {
                                      Value = e.Attribute( "value" ).Value
                                   } );

Was this answer helpful?


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.