Click here to Skip to main content

MitchG92_24 asked:

Open original thread
Hi all,
 
I have an XML file that is created by a powershell script, each XML has differing amounts of nodes within it. An example of a shorter one is below:
 
<Objs Version="1.1.0.1" xmlns="http://schemas.microsoft.com/powershell/2004/04">
  <Obj RefId="0">
    <TN RefId="0">
      <T>...</T>
      <T>...</T>
      <T>...</T>
    </TN>
    <MS>
      <S N="LevelDisplayName">...</S>
      <S N="Message">...</S>
      <S N="MachineName">...</S>
      <I32 N="Id">...</I32>
    </MS>
  </Obj>
  <Obj RefId="1">
    <TNRef RefId="0" />
    <MS>
      <S N="LevelDisplayName">...</S>
      <S N="Message">...</S>
      <S N="MachineName">...</S>
      <I32 N="Id">...</I32>
    </MS>
  </Obj>
</Objs>
 
Now i want to get this XML file and convert it into a useable C# object. I've tried using a deserializer method but as the amount of nodes and what they are tagged as can change, i cannot create a class that accomodates these deserialized variables, so will error everytime.
public static List<T> RetrieveFromXML<T>(string filename, string root)
{
     // Declare an object variable of the type to be deserialized.
     List<T> t;
     using (FileStream fs = new FileStream(filename, FileMode.Open))
     {
          XmlSerializer ser = new XmlSerializer(typeof(List<T>), new  XmlRootAttribute(root));
          t = (List<T>)ser.Deserialize(fs);
      }
 
      return t;
}
 
Is there a way that an object can be dynamically created from the XML, or any other method that you guys have come across?
Tags: C#, XML, convert

Preview



When answering a question please:
  1. Read the question carefully.
  2. Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  3. If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
Let's work to help developers, not make them feel stupid.
Please note that all posts will be submitted under the The Code Project Open License (CPOL).



Advertise | Privacy | Mobile
Web01 | 2.8.141216.1 | Last Updated 26 Mar 2009
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100