Search code examples
c#asp.netxmlreader

how can i literaly read in C# a xml node with multiple atributes?


For a college project i was recently assigned i need to create a hotel system data managment WEB Aplication in C# so one of many functions that it have its got from a xml file all the data that is going to save it in a sql data base, so in the xml file i got multiple nodes that means data of specific tables en the SQL database like:

<Cadena>
<Codigo> CA001 </Codigo>
...
</Cadena>

ok that isnt my problem, my problem and question is that what can i read a node like this:

<TipoHabitacion Cadena="CA001" Hotel="GT001">
.....
</TipoHabitacion>

i mean, i known that the table is "TipoHabitacion" and the Foreign Keys for that table are "Cadena=CA001" and "Hotel=GT001" with those values, how can i differentiate that information knowing that in the same document is the same but with different foreign key like:

<TipoHabitacion Cadena="CA051" Hotel="GT781">
.....
</TipoHabitacion>

and save it with those new values?


Solution

  • Are you asking how to get the attributes of your elements? If so, this is a null-safe solution:

    string cadenaValue = null;
    string hotelValue = null;
    if (node.Attributes != null)
    {
        var cadenaAttribute = node.Attributes["Cadena"];
        if (cadenaAttribute != null) 
            cadenaValue = cadenaAttribute.Value;
    
        var hotelAttribute = node.Attributs["Hotel"];
        if (hotelAttribute != null)
            hotelValue = hotelAttribute.Value;
    }
    
    if (cadenaValue != null)
    {
        Console.WriteLine(cadenaValue);
    }
    
    if (hotelValue != null)
    {
        Console.WriteLine(hotelValue);
    }