c# - Convert xml to custom class using lambda linq -
I have created a custom class trying to parse an XML document I have successfully figured out how to document Parsing, but for some reason I have to do this in the IEnumerable instead of a single instance of my custom class, it is very easy to show the code in depth, so see the code snippet below .
Job Code
IEnumerable & lt; Ping & gt; Ping = xmlDoc.Descendants ("p = & gt; new ping {TRAN_ID = (string) P. element (" TRAN_ID "), MILOC = (string) P. element (" MILOC "), traffic = (string) p. Element ("TRANDATE"), TRANTIME = (string) P.Ellement ("TRANTIME"), COUNTRY = (string) P.Element ("COUNTRY")}); Its use Results in ...
foreach (ping in ping p) {cmd.Parameters.AddWithValue ("@ TRAN_ID", p .TRAN_ID); Cmd.Parameters.AddWithValue ("@ MILOC ", PMILOC); Cmd.Parameters.AddWithValue (" @ SITE_REF "," ");} ... in the database
The desired code idea
Ping Ping = (ping) xmldoc (p = & gt; new ping {TRAN_ID = (string) P. element ("TRAN_ID"), MILOC = (string) P. element ("MILOC"), trout = (string ) .P .Element ("TRANDATE"), TRANTIME = (string) p.Element ("TRANTIME"), COUNTRY = (string) p.Element ("COUNTRY")}); // ... other operations and database functions ... CMD. Parameter. Advant Value ("@ TRAN_ID", ping. TRAN_ID); Cmd.Parameters.AddWithValue ("@MILOC", Ping. MILOC); Cmd.Parameters.AddWithValue ("@SITE_REF", "");
You think you should only first or Single () or whatever - to say that you want only a result (first or only result - other options are available):
Ping Ping = xmlDoc.Descendants ("PING_SEND"). (...) first (); Basically, this issue is that after Descendants (...). (...) You get an sequence ping of references, while you only want one.
If there is more than one PING_SEND element can be - or none - you really need to think what you want to do in that situation according to your needs , LINQ provides a variety of methods to assist you based on your help:
-
first -
single/> -
last -
first and default -
single default defaults / Li> >
Comments
Post a Comment