Please help. Is it possible to form a structure from a file and fill in the fields ( Marshal.PrtToStructure )?

Xml file, we have lines

<ID>b7131367-82e3</ID> <Layer>Channel</Layer> <MinFrameLength>20</MinFrameLength> <...>???</...> <MaxFrameLength>65535</MaxFrameLength> 

How to write <ID> , <Layer> , <MinFrameLength> , <...>``<MaxFrameLength> and assign values ​​to b7131367-82e3 , Channel , 20 , ??? , 65535 respectively.?

Input data: xml format file (number of lines, order, name may be different, that is, we do not know).

Task 1. To form a structure from a file where the line is a field of the structure.
Task 2. Fill the structure.

  • one
    It is possible, but the question is incomprehensible. What do you have in the file and what structure do you want to create? - Nick Volynkin
  • The xml file, we have the lines <ID> b7131367-82e3 </ ID> <Layer> Channel </ Layer> <MinFrameLength> 20 </ MinFrameLength> <MaxFrameLength> 65535 </ MaxFrameLength>. How to write <ID>, <Layer>, <MinFrameLength>, <MaxFrameLength> into the structure and assign values ​​to b7131367-82e3, Channel, 20, 65535, respectively. - Kostya_12
  • Try using XML deserialization. - Pavel Mayorov
  • one
    I wonder who closes this question as "it is necessary to clarify the details"? It seems like enough details to answer. - PashaPash
  • @PashaPash: now enough, withdrew voice. - Nick Volynkin

1 answer 1

The Marshal class is designed to work with unmanaged code. You need the usual Xml deserialization:

for file

 <?xml version="1.0" encoding="utf-8"?> <SomeRootNode> <ID>b7131367-82e3</ID> <Layer>Channel</Layer> <MinFrameLength>20</MinFrameLength> <MaxFrameLength>65535</MaxFrameLength> </SomeRootNode> 

The code will look something like this:

 using System.IO; using System.Xml.Serialization; namespace ConsoleApplication1 { [XmlRoot("SomeRootNode")] public struct MyStruct { public string ID { get; set; } public string Layer { get; set; } public byte MinFrameLength { get; set; } public ushort MaxFrameLength { get; set; } } class Program { static void Main(string[] args) { XmlSerializer serializer = new XmlSerializer(typeof(MyStruct)); using (var fileStream = File.OpenRead(@"C:\Temp\2.xml")) { var instance = (MyStruct)serializer.Deserialize(fileStream); } } } } 
  • and by default, wouldn't he try to smappit attributes to the fields? - Grundy
  • one
    @Grundy is not. Well, I cheat - Edit / Paste Special / Paste XML as Classes :) - PashaPash
  • And if the file structure changes, can we form a structure from the file and assign the appropriate value? - Kostya_12
  • @PashaPash, cool! :-) I didn’t even know that it was possible, usually I used some third-party services - Grundy
  • one
    @BOPOH Well, if you stick to the original wording, then through Marshal.PrtToStructure this cannot be done. 100%. and there were not my improvements - I moved his comment to the body of the question :) - PashaPash