Search code examples
xmlxsltxsdxml-serializationxml-deserialization

"Database" structure in XML file


So I have to define a "database" in an xml document that has to have a school, grades, rooms, courses and students and afterwards I have to write some classes in C# that has to get and save data to the xml file with the help of Deserialization and Serialization. But the problem is I don't know how I should structure the XML file, right now my file looks like this:

<?xml version="1.0" encoding="utf-8" ?>
<School>
   <Grades>

   </Grades>
   <Rooms>

   </Rooms>
   <Courses>

   </Courses>
   <Students>

   </Students>
</School>

But I have been wondering if this might be a better way:

<?xml version="1.0" encoding="utf-8" ?>
<School>
   <Grades>
      <Rooms>
         <Courses>
            <Students>

            </Students>
         </Courses>
      </Rooms>
   </Grades>
</School>

Or maybe there is some third way I'm overlooking, any help would be appreciated


Solution

  • This question is opinion-based. So, this is just my opinion:

    Choose the first layout and use attribute @IDs to link between them.
    For example:

    <?xml version="1.0" encoding="utf-8" ?>
    <School>
       <Grades>
         <Grade id="gr1">...</Grade>
       </Grades>
       <Rooms>
         <Room id="rm1">...</Room>    
       </Rooms>
       <Courses>
         <Course id="crs1">
           <RoomNr>rm1</RoomNr>  <!-- Referring to the Rooms/Room/@id rm1 -->
           ...
         </Course>
       </Courses>
       <Students>
         <Student id="1">
           <Course>crs1</Course> <!-- Referring to the Courses/Course/@id crs1 -->
           <Course>...</Course>
         </Student>
       </Students>
    </School>
    

    This layout is easily query-able and changing the links won't significantly change the layout.

    For example (Because you tagged your question with ):

    • Retrieving all <Student>s can be done with the XPath-1.0 expression

      /School/Students/Student
      
    • Retrieving all <Student>s which visit a certain course (e.g. crs1)

      /School/Students/Student[Course='crs1']
      

    ...and so on.