0

lets say i have model structure like this

<MyObject>
    <Files>
        <File>1</File>
        <File>2</File>
    </Files>
    <Directories>
        <File>3</file>
    </Directories>
</<MyObject>

when i want to add some new file to Files - it is easy, i just have to to create model and deserialize it to this model:

class MyObject
{
    List<Files> Files
    List<Files> Directories
}

Then just Files.Add(new File(...) and then serialize it again - it will work

But i dont know how to handle situation, where i would not know all the elemenets existing in xml file - i know that there are only files and directories (like above) and would like only to modify them - but i have to leave the rest alone - f.e. after i add new file to files/directories and i will again serialize it and write to xml, i would like to have serialized xml files with attributess that are left i don't know them

let say the xml file would looks like

<MyObject>
    <Files>
        <File>1</File>
        <File>2</File>
    </Files>
    <Directories>
        <File>3</file>
    </Directories>
    <SomeAttrib1> ... </SomeAttrib1>
    <SomeAttrib2> ... </SomeAttrib2>
</<MyObject>

And i dont know that xml contains SomeAttrib1, SomeAttrib2 (in case i would know, i would just add to model

Object SomeAttrib1 

and it would be serialized

but in case i cant be sure what will be included in xml file - what should i do?

I Use c# with System.Xml.Serialization;

Skin
  • 9,085
  • 2
  • 13
  • 29
pawelek91
  • 99
  • 8
  • You need another class which contains the child attributes, public class Attributes { public string attr1; string public att2;} You could make the class contain a list of objects so you do not need a class for every combination of child attributes. – jdweng Jan 13 '23 at 10:41
  • please read my post - problem is that i won't know other elements of xml – pawelek91 Jan 13 '23 at 10:43
  • Xml serialize/deserialize requires that you know the structure of the input. When you do not know the structure use a class like Xml Linq to handle more general case of Xml Inputs. – jdweng Jan 13 '23 at 10:48
  • Use [`XmlAnyElementAttribute`](https://learn.microsoft.com/en-us/dotnet/api/system.xml.serialization.xmlanyelementattribute): add a `[XmlAnyElement] public XmlElement[] ExtraElements { get; set; }` property as shown in the answer by Gene to [XmlSerializer: keep unknown elements](https://stackoverflow.com/q/34787284/3744182). – dbc Jan 29 '23 at 00:58

0 Answers0