简体   繁体   中英

Create dynamic object with hierarchy from xml and c#

I want to create a dynamic object from a string of XML. Is there an easy way of doing this?

Example String.

<test><someElement><rep1>a</rep1><rep1>b</rep1></someElement></test>

I'm trying to create an mvc editor for passing data through nvelocity and would like people on the front end to input xml as there data for parsing.

Thanks in advance.

You need 2 things to achieve this : 1) Valid xml 2) C# class which has same data members as in your input xml.

You need to create one object of C# class then enumerate through all the elements of xml and when by using switch for each of the element name, you can take inner text property of that element and assign it to respective data member of object. C# code might look like following (you need to fill in the gaps):

class test {
  List<string> someElement;
}

class xmlEnum 
{
 static test createObject(string inputXml) 
 {
     test t = new test();
     // load input xml in XmlDocument class
     // and start iterating thorugh all the elements
     swithc(elementName)
     {
        case rep1:
            t.someElement.add(element.innerText);
            break;
         // some more cases will go here

     }
   // finally return the object;
  return t;
 }
}

I hope this will help you.

I don't think there's a ready-made dynamic solution to this. If I understand your question correctly, you would like to do something like this.

SomeDynamicXmlObject test = new SomeDynamicXmlObject(yourteststring);
var rep1 = test.SomeElement.rep1;

The closest I can think of you could get to that, is to use XElement classes, something like this:

XElement test = XElement.Parse(yourteststring);
var rep1 = test.Element("SomeElement").Element("rep1");

If that's not good enough, I'm afraid you will have to write something yourself that will parse the xml and create the object on the fly. If you know in advance what the xml will look like, you could use shekhars code, but I guess from your comments that you don't.

If you have schema for xml available and if this is needed in dev/build environment then a round about way to do this will be

  1. Use XSD tool to parse schema and generate code from it
  2. Build the generated code using command line complier or compiler services to generate assmebly. Now you have a type available there that can be used. Needless to say this will be a quite slow and out-of-proc tools will be used here.

Another (not an easy way but faster) way that would not have dev env dependencies would be to parse your xml and generate dynamic type using reflection. See this article to check how to use Reflection.Emit

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM