LINQ to XML: parsing an XML file that one of node s represents the type of another node

Helo!

Is it possible to use the string value of one node that tells what type of field is represented in another node using LINQ to XML?

For instance:

<node>
  <name>nodeName</name>
  <type>string</type>
</node>
<node>
  <name>0</name>
  <type>bool</type>
</node>
<node>
  <name>42</name>
  <type>int</type>
</node>

Thanks in advance

+3
source share
2 answers

Well, you won't get a good statically typed API, given that type information is known only at runtime, but you can easily write an extension method on XElement that looks for the corresponding subelements and returns System.Object. For example (untested):

public static object ParseValue(this XElement element)
{
    XElement name = element.Element("name");
    XElement type = element.Element("type");
    // Insert error handling here :)

    switch (type.Value)
    {
        case "int":
            return int.Parse(name.Value);
        case "string":
            return name.Value;
        case "bool":
            return name.Value == "1"; // Or whatever
        default:
            throw new ArgumentException("Unknown element type " + type.Value);
    }
}

This is not how I would develop a data format, but if it is imposed on you ...

+3
source
public static void Main() {
    var xmlNodes = new XElement( "Nodes",
        new XElement( "Node",
            new XElement( "Name", "nodeName" ),
            new XElement( "Type", "string" )
        ),
        new XElement( "Node",
            new XElement( "Name", "True" ),
            new XElement( "Type", "bool" )
        ),
        new XElement( "Node",
            new XElement( "Name", "42" ),
            new XElement( "Type", "int" )
        )
    );

    var converters = new Dictionary<string,Func<string,object> >  {
        { "string", val => val },
        { "bool", val => Boolean.Parse( val ) },
        { "int", val => Int32.Parse( val ) }
    };

    var values = 
        from node in xmlNodes.Elements( "Node" )
        select converters[ node.Element( "Type" ).Value ]( node.Element( "Name" ).Value );

    foreach( var value in values )
        Console.WriteLine( value.GetType().ToString() + ": " + value );
}
+2
source

Source: https://habr.com/ru/post/1699634/


All Articles