Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 924617
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T19:23:03+00:00 2026-05-15T19:23:03+00:00

I’ve ran into a problem and wondered if there’s simple way of solving it.

  • 0

I’ve ran into a problem and wondered if there’s simple way of solving it.

Here I have a XML template, defining some properties and their values.

<Properties>
  <Property name="ID">10000</Property>
  <Property name="Name">
    <SubProperty name="FirstName">Foo</SubProperty>
    <SubProperty name="LastName">Bar</SubProperty >
  </Property>
</Properties>

All I what is to extract the Properties/subProperties defined in the template to generate a new XML file, with all values attached, something like

<Items>
  <ID>10000</ID>
  <Name>
    <FirstName>Foo</FirstName>
    <LastName>Bar</LastName>
  </Name>
</Items>

Since I don’t know the content of the template in design time, I tried to load it and created a List class use LINQ, but cannot get the result above when serialize it directly. So instead of create a List class I created a dynamic object using Reflection.Emit and then serialize the object to XML.


private static readonly XDocument doc = XDocument.Load("Template.xml");

static void Main(string[] args) {
    var newType = CreateDynamicType();
    var newObject = Activator.CreateInstance(newType);
    var properties = newType.GetProperties();
    foreach (var property in properties) {
        // assign values
    }
    SerializeToXml(newObject);
}

private static Type CreateDynamicType() {

    AssemblyName assemblyName = new AssemblyName() { Name = "DynamicTypeAdapter" };
    AssemblyBuilder assembly = 
        Thread.GetDomain().DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
    ModuleBuilder module = 
        assembly.DefineDynamicModule(assembly.GetName().Name, false);
    TypeBuilder type = module.DefineType("Items", TypeAttributes.Public | TypeAttributes.Class);

    foreach (var p in doc.Descendants("Property")) {
        string pName = p.Attribute("name").Value;
        TypeBuilder subType = module.DefineType(pName, TypeAttributes.Public | TypeAttributes.Class);
        foreach (var sp in p.Descendants("SubProperty")) {
            CreateDynamicProperty(subType, sp.Attribute("name").Value, typeof(string));
        }
        var propertyType = subType.CreateType();
        CreateDynamicProperty(type, pName, propertyType);
    }

    return type.CreateType();
}

private static void CreateDynamicProperty(TypeBuilder typeBuilder, string propertyName, Type propertyType) {
    PropertyBuilder property = typeBuilder.DefineProperty(propertyName,
    PropertyAttributes.None, propertyType, new Type[] { typeof(string) });

    FieldBuilder field = typeBuilder.DefineField("_" + propertyName, propertyType, FieldAttributes.Private);

    MethodAttributes GetSetAttributes = MethodAttributes.Public | MethodAttributes.HideBySig;

    MethodBuilder getMethod =
        typeBuilder.DefineMethod("get_value", GetSetAttributes, propertyType, Type.EmptyTypes);

    ILGenerator getIL = getMethod.GetILGenerator();
    getIL.Emit(OpCodes.Ldarg_0);
    getIL.Emit(OpCodes.Ldfld, field);
    getIL.Emit(OpCodes.Ret);

    MethodBuilder setMethod =
            typeBuilder.DefineMethod("set_value", GetSetAttributes, null, new Type[] { typeof(string) });

    ILGenerator setIL = setMethod.GetILGenerator();
    setIL.Emit(OpCodes.Ldarg_0);
    setIL.Emit(OpCodes.Ldarg_1);
    setIL.Emit(OpCodes.Stfld, field);
    setIL.Emit(OpCodes.Ret);

    property.SetGetMethod(getMethod);
    property.SetSetMethod(setMethod);
}

It works fine but is there any simple way of doing this?
Any comment is appreciated. Thanks

  • 1 1 Answer
  • 3 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-15T19:23:04+00:00Added an answer on May 15, 2026 at 7:23 pm

    If all you want to do change (transform) one XML format to another XML format then I think the approach you are taking is not the most appropriate. There are other APIs in the framework that support this kind of functionality. In your case the requirement seems rather simple, so I would opt for the Linq To Xml option. The following is a quick example, which produces the desired output.

    XDocument doc = XDocument.Parse(@"<Properties>
                    <Property name='ID'>10000</Property>
                    <Property name='Name'>
                        <SubProperty name='FirstName'>Foo</SubProperty>
                        <SubProperty name='LastName'>Bar</SubProperty>
                    </Property>
                </Properties>");
    
    XElement items = new XElement("Items", 
                                   from property in doc.Descendants("Property")
                                   select new XElement((string)property.Attribute("name"),
                                                        // If there are no child elements (SubPropety)
                                                        // get the property value
                                                        property.HasElements ? null : (string)property,
                                                        // Another way for checking if there are any child elements
                                                        // You could also use property.HasElements like the previous statement
                                                        property.Elements("SubProperty").Any() ?
                                                        from subproperty in property.Elements("SubProperty")
                                                        select new XElement((string)subproperty.Attribute("name"),
                                                                            (string)subproperty) : null)
    
                              );
    

    A few resouces that may be of help include:

    http://msdn.microsoft.com/en-us/library/bb387098.aspx

    http://msdn.microsoft.com/en-us/library/bb308960.aspx

    http://iqueryable.com/2007/08/03/TransformingXMLWithLINQToXML.aspx

    http://www.codeproject.com/KB/linq/LINQtoXML.aspx

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have just tried to save a simple *.rtf file with some websites and
I ran into a problem. Wrote the following code snippet: teksti = teksti.Trim() teksti
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
this is what i have right now Drawing an RSS feed into the php,
I have a French site that I want to parse, but am running into
I am currently running into a problem where an element is coming back from
I have some data like this: 1 2 3 4 5 9 2 6
For some reason, after submitting a string like this Jack’s Spindle from a text
I have a jquery bug and I've been looking for hours now, I can't

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.