Solved

Serialize a class

Posted on 2004-08-26
6
1,694 Views
Last Modified: 2008-03-10
I'm trying to serialize a custom class that needs to use multiple elements of the same name.  I've tried using xmlarray, but it wraps them in another element.  


I want my xml to look like this.
<xmlroot>
     <element>some text</element>
     <element>some more text</element>
</xmlroot>

My code:
[Serializable(), XmlRoot("xmlroot")]
public class xmlroot
{
      [XmlArray("element")]
      public ArrayList MyProp1 = new ArrayList();
       
      public xmlroot()
      {
           MyProp1.Add("some text");
           MyProp1.Add("some more text");
           

      }
}

I've also tried this, but it throws reflection errors when trying to serialize:

[Serializable(), XmlRoot("xmlroot")]
public class xmlroot
{
      [XmlElement("element")]
      public string MyProp1;
     
      [XmlElement("element")]
      public string MyProp2;

      public xmlroot()
      {
           MyProp1 = "some text";
           MyProp2 = "some more text";
      }
}

After I serialize, it looks like this:
<xmlroot>
     <element>
           <anyType xsi:type="string">some text</anyType>
           <anyType xsi:type="string">some more text</anyType>
     </element>
</xmlroot>
0
Comment
Question by:darthg8r
6 Comments
 
LVL 1

Expert Comment

by:johanjohansson
Comment Utility
What if you make the xmlroot class into a list:

[Serializable(), XmlRoot("xmlroot")]
public class xmlroot : CollectionBase
{
   [XmlElement("element")]
   public string this[int index]
   {
      get { ... }
      set { ... }
   }

   public int Add( string element ) { ... }
   public void Remove( int index ) { ... }
}
0
 
LVL 1

Expert Comment

by:johanjohansson
Comment Utility
You can also feed your XML into the Xsd.exe tool to get the object model (classes) defined for you.
0
 
LVL 2

Accepted Solution

by:
sonicblis earned 250 total points
Comment Utility
Here is the serializable class:

[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public class xmlroot {
   
    [System.Xml.Serialization.XmlElementAttribute("element", Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=true)]
    public xmlrootElement[] Items;
}

public class xmlrootElement {
   
    [System.Xml.Serialization.XmlTextAttribute()]
    public string Value;
}

Steps to producing this code:

1. Create the xml file you want to end up with in notepad (or an editor of your choice)
2. Use the xsd.exe tool (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cptools/html/cpconXMLSchemaDefinitionToolXsdexe.asp) to generate an xsd [xsd -c -l:c# yourxml.xml]
3. Use the xsd.exe tool to generate the classes that will be serialized appropriately [xsd -c -l:c# yourschema.xsd]
0
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 
LVL 7

Expert Comment

by:NipNFriar_Tuck
Comment Utility
What has already been stated is true... As to why you ended up with the xml like you did is that an Array is translated into an XML Sequence and since you did not use an attribute to specify the type of data in the array the translation asumed anyType.  Hope this helps...
0
 
LVL 10

Expert Comment

by:123654789987
Comment Utility
Try this

[Serializable(), XmlRoot("xmlroot")]
public class XmlRoot:  CollectionBase
      {
            
      public int Add(Element element)
            {
                  return this.InnerList.Add(element);
            }


            [XmlArrayItem("Element")]
            public  Element this[int index]
            {
                  get
                  {
                        return this.InnerList[index] as Element ;
                  }
                  set
                  {
                        this.InnerList[index]=value;
                  }
            }

      }
0
 

Expert Comment

by:_dataking_
Comment Utility
An arraylist member is properly serialized as shown below, assuming the objects in the arraylist is of type "Item":

// This attribute enables the ArrayList to be serialized:
[System.Xml.Serialization.XmlArray("Items")]
// Explicitly tell the serializer to expect the Item class
// so it can be properly written to XML from the collection:
[System.Xml.Serialization.XmlArrayItem("item",typeof(Item))]
public ArrayList myArrayList;

HTH
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

This article describes a simple method to resize a control at runtime.  It includes ready-to-use source code and a complete sample demonstration application.  We'll also talk about C# Extension Methods. Introduction In one of my applications…
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now