Serializing array of userdefined types

Hello,

I want to have a class that contains only a collection of another class.
For example:

public __gc class Alignment {
public:
  Alignment();
  ...
};

// Probably using XmlIncludeAttribute such as this is wrong...
[System::Xml::Serialization::XmlIncludeAttribute(__typeof(Alignment))]
public __gc class Alignments : public System::Collections::ArrayList {
public:
  Alignments();
  ...
};

I figured I could use Alignments like this:
Alignment* alignment = new Alignment;
Alignments* alignments = new Alignments;
alignments->Add(alignment);

BTW, I am using XmlSerializer and XmlTextWriter.

But I get exceptions:
--------- Exception Data ---------
Message: There was an error reflecting type 'LX.LandXML'.
Exception Type: System.InvalidOperationException
Source: System.Xml
StrackTrace:    at
System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(TypeModel
model, String ns, ImportContext context, String dataType, Boolean repeats)
   at
System.Xml.Serialization.XmlReflectionImporter.ImportElement(TypeModel
model, XmlRootAttribute root, String defaultNamespace)
   at System.Xml.Serialization.XmlSerializer..ctor(Type type, String
defaultNamespace)
   at System.Xml.Serialization.XmlSerializer..ctor(Type type)
   at main(Int32 argc, SByte** argv) in c:\documents and
settings\daniel.sbg\my documents\visual studio
projects\managed_test\test1\test1.cpp:line 22
TargetSite: System.Xml.Serialization.TypeMapping
ImportTypeMapping(System.Xml.Serialization.TypeModel, System.String,
ImportContext, System.String, Boolean)
--------- Exception Data ---------
Message: There was an error reflecting property 'Alignments'.
Exception Type: System.InvalidOperationException
Source: System.Xml
StrackTrace:    at
System.Xml.Serialization.XmlReflectionImporter.ImportStructLikeMapping(StructModel
model, String ns)
   at
System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(TypeModel
model, String ns, ImportContext context, String dataType, Boolean repeats)
TargetSite: System.Xml.Serialization.StructMapping
ImportStructLikeMapping(System.Xml.Serialization.StructModel,
System.String)


What is the usual way to serialize a collection of the same type of
objects? The end result I am after is this:
  <Alignments>
    <Alignment name="Centreline>
    </Alignment>
    <Alignment name="LeftCatch">
    </Alignment>
    ... arbitrary number of Alignments
  </Alignments>

Any pointers or references very much appreciated.
Thanks!

-- 
Daniel
0
someone913 (592)
5/19/2004 10:09:36 AM
dotnet.xml 7266 articles. 0 followers. Follow

3 Replies
529 Views

Similar Articles

[PageSpeed] 4

Hello, Daniel!
You wrote  on Wed, 19 May 2004 12:09:36 +0200:


[Sorry, skipped]


 DL> What is the usual way to serialize a collection of the same type of
 DL> objects? The end result I am after is this:
 DL>   <Alignments>
 DL>     <Alignment name="Centreline>
 DL>     </Alignment>
 DL>     <Alignment name="LeftCatch">
 DL>     </Alignment>
 DL>     ... arbitrary number of Alignments
 DL>   </Alignments>

 DL> Any pointers or references very much appreciated.
 DL> Thanks!

Well, maybe this example be right for you.
[code]
#using <mscorlib.dll>
#using <System.Xml.dll>

using namespace System;
using namespace System::Collections;
using namespace System::Xml;
using namespace System::Xml::Serialization;
using namespace System::IO;

public __gc class foo
{
public:
 foo()
 {
 }

 foo(System::String* s)
 {
  _s = s;
 }
public:
 [XmlAttributeAttribute(S"name")]
 System::String* _s;
};

public __gc class foos
{
public:
 foos()
 {
  arr = new ArrayList();
 }
public:
 [XmlArray(S"Alignments")]
 [XmlArrayItemAttribute(S"Alignment",__typeof(foo))]
 ArrayList* arr;
};

int _tmain()
{
    XmlSerializer* xs = new XmlSerializer(__typeof(foo));
 foo* f = new foo(S"hi!");
 Text::StringBuilder* sb = new Text::StringBuilder();
 StringWriter* sw = new StringWriter(sb);
 xs->Serialize(sw,f);
 sb->Append(S"\n-------\n");
 foos* fs = new foos();
 fs->arr->Add(f);
 xs = new XmlSerializer(__typeof(foos));
 xs->Serialize(sw,fs);
 Console::WriteLine(sb->ToString());
 return 0;
}
[/code]

With best regards, Alex Shirshov.


0
nomail7826 (11)
5/20/2004 8:39:27 AM
On Thu, 20 May 2004 12:39:27 +0400, Alex Shirshov wrote:

> Hello, Daniel!
> You wrote  on Wed, 19 May 2004 12:09:36 +0200:

[...]

> With best regards, Alex Shirshov.

Thanks a lot Alex! This is just what I needed.

-- 
Daniel
0
someone913 (592)
5/24/2004 9:17:14 AM
On Wed, 19 May 2004 12:09:36 +0200, Daniel Lidstr´┐Żm wrote:

> Hello,

[...]

> What is the usual way to serialize a collection of the same type of
> objects? The end result I am after is this:
>   <Alignments>
>     <Alignment name="Centreline>
>     </Alignment>
>     <Alignment name="LeftCatch">
>     </Alignment>
>     ... arbitrary number of Alignments
>   </Alignments>

New problem: The end result I am after is this:
  <Alignments name="Road Project">
    <Alignment name="Centerline" />
    <Alignment name="Centerline 2" />
    ... arbitrary number of these
  </Alignments>

What I get right now is this:
  <Alignments name="Road Project">
    <Alignment>
      <Alignment name="Centerline" />
      <Alignment name="Centerline 2" />
    </Alignment>
  </Alignments>

I am doing it this way (everything is in namespace LX):

public __gc class LandXML {
public:
  LandXML() { }
 
  __property LX::Alignments* get_Alignments() { return m_arr; }
  __property void set_Alignments(LX::Alignments* a) { m_arr = a; }

protected:

  LX::Alignments* m_arr;

};

public __gc class Alignment {
public:
  Alignment() { }
  [XmlAttributeAttribute("name")]
  __property String* get_name() { return m_name; }
  __property void set_name(String* n) { m_name = n; }

protected:
  String* m_name;
};

public __gc class Alignments {
public:
  Alignments() { m_array = new ArrayList(); }

  [XmlAttributeAttribute("name")]
  __property System::String* get_name() { return m_name; }
  __property void set_name(System::String* n) { m_name = n; }

  [XmlArrayItemAttribute(Type=__typeof(LX::Alignment))]
  __property ArrayList* get_Alignment() { return m_array; }
  __property void set_Alignment(ArrayList* arr) { m_array = arr; }

  void Add(LX::Alignment* alignment) { m_array->Add(alignment); }

protected:

  String* m_name;
  ArrayList* m_array;

};


Somewhere in main.cpp I set the elements of a LandXml object, and serialize
object to disk:

    XmlSerializer* ser = new XmlSerializer(__typeof(LandXML));
    XmlTextWriter* writer = new XmlTextWriter("out.xml", Encoding::UTF8);
    // write a human readable file
    writer->Formatting = Formatting::Indented;
    LandXML* land_xml = new LandXML();
    Alignment* alignment = new Alignment;
    Alignment* alignment2 = new Alignment;
    alignment->name = "Centerline";
    alignment2->name = "Centerline 2";
    land_xml->Alignments->Add(alignment);
    land_xml->Alignments->Add(alignment2);
    land_xml->Alignments->name = "Road Project";
    ser->Serialize(writer, land_xml);
    writer->Close();


So it seems I need to remove one level of Alignment, only I don't really
know how to do it. If I create a class Alignment that instead of having a
ArrayList as member, I let it inherit from ArrayList. Then it doesn't
matter if I have a attribute called name, because it will not be
serialized. How can I solve this problem? Any help in form of samples,
links, docs, very much appreciated.
Thanks!

-- 
Daniel
0
someone913 (592)
5/24/2004 2:05:13 PM
Reply:

Similar Artilces:

How to stop type going from right to left from cursor
In the middle of a document my cursor stopped dead and further typing started producing letters from right to left, instead of normal progression. Help! Is a right-to-left language enabled on your machine (Hebrew or Arabic)? You may have accidentally hit a keyboard shortcut to change input language (LeftAlt+Shift), but since you didn't change the keyboard, you'd still be typing English letters. Or maybe if you ever pasted something into your document, it brought with it one of those language labels. Or you might have "Detect language automatically" turned on. O...

Type Network Password keeps coming up when send or receive email
Our corporate office installed spam filtering software today. I am at remote site. I had to use different SMTP and now Outlook wants a network password. I type it in but it won't save it and keeps coming back up. Sometimes mail still goes out, and I think comes in as well, but I don't know. How do I get that logon screen to go away? Also, I bought the computer in mid 2002 and don't know if this is Outlook 2000 or 2002. How do I know? Act! says it is an old version and needs to be updated, but it was installed by Dell at the same time. ...

Wrong Data Type - Too Many Characters
I have a form [FA1_OrgMaster] that has a Combo Box [cboCounties]. The cbo's Row Source is a Query with 2 columns - [TYaa_CountyNumber] - Integer, and [TYaa_CountyName] - Text 50 characters. The first column - CountyNumber - is Bound, but only the 2nd is displayed to the user in the cbo. I have a Form Open Event Procedure - but it doesn't affect the cbo. I have a Form Load Procedure that does: _______________ Private Sub Form_Load() On Error GoTo HandleError Me!cboOrgs = Null Me!cboCounties = Null Me!cboCounties = "Choose County" Me!cboCounties.SetF...

How to Creating Array
Hi all, I got macro (see below) Private Function LabelNormal() On Error Resume Next Dim ctl As Control For Each ctl In Me.Controls If TypeOf ctl Is Label And ctl.Name <> "Label10" And ctl.Name <> "Label9" Then With ctl .SpecialEffect = 1 'Raised .BackColor = 8421504 'Grey .ForeColor = 16777215 'White .FontWeight = 400 'Normal End With End If Next End Function the above macro fine but I want to change the line where it say If TypeOf ctl Is Labe...

Installing with new serial number
Version: 2004 Operating System: Mac OS X 10.4 (Tiger) Processor: Intel I only use Word and Entourage, and both have gotten so buggy that they're interfering with my livelihood. If I reinstall Office using one of the other three serial numbers, will that affect any of my existing documents? And will it help get rid of the bugs? Thanks for any help you feel moved to offer this non-techie. On 3/18/09 1:00 PM, "writty@officeformac.com" <writty@officeformac.com> wrote: > I only use Word and Entourage, and both have gotten so buggy that they're > interfering with m...

Use Julian Date To Create Serial Number
I am trying to find a way to create a unique serial number based upon the current julian date + an increment counter. I have sort of done this however the julian date function is not static and all the serial numbers change each day. I need to create be able to create the serial number (maybe by clicking on a cell) and then once the number populates the cell, it remains fixed. Any suggested would be welcome. Hi you have to use an event procedure for this. See: http://www.mcgimpsey.com/excel/timestamp.html -- Regards Frank Kabel Frankfurt, Germany "antho10359" <antho10359...

Self Diagnosis & RunTime Type Handling
I'm trying to write some self diagnostics and think it's worth checking that objects have constructed themselves properly by using the IsKindOf macro. Is this a worthwhile exercise? Any sensible ways of checking that my application is / isn't working properly? AND I've got a specific query with the IsKindOf macro. class A : public CObject { Declare_Serial(CObject) etc etc class B : public A { Declare_Serial(B) etc etc class C : public A etc etc but if I have a class of type B or C ->IsKindOf (RUNTIME_CLASS (A) fails but ->IsKindOf (RUNTIME_CLASS (C...

Array
I'm trying to summarize the number of people who attended any class, by supervisor. Data for 3,000 employees is on one sheet and the summary on another. Other people are entering the source data, and have consistently found ways to break my hidden columns that had formulas to check columns CFI and DGJ and EHK -- so the easiest obvious solution isn't workable. I've tried to create an array formula on my summary sheet, but it's not returning the expected results, so I'm off track. I have array formulas to count people by class by supervisor working, but coun...

Regional Settings / Finding out Array separator characters
Hello ! I'm running Excel on a Portuguese Windows XP system. I'm trying to create some array constants but haven't been able to do it. As for VERTICAL arrays, I use the ";" (semicolons) and it works fine, like this : ={"A";"B";"C"} However, when I try to create a HORIZONTAL array, I try to use the "," (commas) as separators but I can't even enter the formula. It complains. How do I find out WHICH is the Array separator character in this case ? Notice that in Portuguese, Decimal point is comma. Thanks ! ...

Problem with Array and MIN function
I want to find the minimum numerical value in column E based on the text value of column D. The range of the data is D3:E40, however the D3:D40 is complete, but E3:E6 has data but E7 to E40 are blank and will have values as they are completed. The formula used is {=MIN(IF(D3:D40=AA2,E3:E40))} returns 0 but {=MIN(IF(D3:D6=AA2,E3:E6))} returns the actual value. AA2 is a text value. What am I doing wrong? Hi try: {=MIN(IF((D3:D40=AA2)*(E3:E40<>""),E3:E40))} -- Regards Frank Kabel Frankfurt, Germany Campbell wrote: > I want to find the minimum numerical value in column E...

Field type question
Can you use a check box instead of a radio button? ...

type specified in the Imports 'System.Web.UI.WebControls.Expressions' doesn't ...
Namespace or type specified in the Imports 'System.Web.UI.WebControls.Expressions' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. ... I don't know what I did to make VS2010 hate me (just kidding) But now I get the above for many of my pages. And the <%@ Page Language="VB" MasterPageFile="~/Main.master"... line is shown as the culprit. I searched and find I never reference that name space> Got any suggeations that might help? Google...

can't type "HSA" into a cell
I have a part name HSA but can't type it into any cell, because Excel will change it to HAS automatically? Please help. Thanks, Excel is trying to "correct" your spelling. To avoid: Tools > Options... > Spelling > Autocorrect Options > Autocorrect and fix the dictionary -- Gary''s Student - gsnu200909 "ongcong" wrote: > I have a part name HSA but can't type it into any cell, because Excel will > change it to HAS automatically? Please help. > Thanks, > ...

How to display array of strings via Format-Wide
Has anybody tried to display collection of strings using Format-Wide? It works, but everytime only one column is used. Example: [1]:> '1', '2', '3', '4', '5' | format-wide -autosize 1 2 3 4 5 I have no idea how to persuade Posh to use more columns or accept - autosize switch. The only way that works is this one: '1','22','333','4444','55555' | % { new-object psobject -prop @{This= $_}} | Format-Wide -Property This -autosize i.e. creating new psobject with a noteproperty [string]@('1'...

Through cluster API's how to get EVS IP address and RESOURCE "TYPE" value?
Hi, Question : Through cluster API's how to get EVS IP address and RESOURCE "TYPE" value? I am trying to get EVS ( exchagne virtual server ) inforamtion using cluster API's. The flow is somewhat like this. 1. get computer name using "GetComputerName" 2. use "OpenCluster" using this computer name and get a handle to the cluster 3. call "ClusterOpenEnum" by passing CLUSTER_ENUM_GROUP to open enumrator on groups 4. call "ClusterEnum" to emumerate through the objects and to get the name of the group 5. call "OpenClusterGroup" f...

Serialization
Experienced members, I need some advice, or maybe I am missing something simple. I have 2 classes. public class Manager public property Controls as arraylist public function CreateObject(byval type as Types) as IObject end class public class myControl implement IObject public property Controls as arraylist public property Parent as IObject end class I have a circular reference when I do this; dim man as new manager dim c1 as new myControl dim c2 as new myControl c1.controls.add(c2) c2.Parent = c1 man.controls.add(c1) Ok, now I have a object tree. I would like to serialize the...

How to obtain file pointer and file name in Serialize()?
I am using Serialize() method in my DOC to open a file. 1) How can I retrieve the file pointer? and 2) How can I obtain the full path file name of the file being opened? Thank you. If you have implemented Serialize() properly , the method should be passed a CArchive parameter: void CMyObject::Serialize( CArchive& archive ); You can then just use: const CFile* fp = archive.GetFile(); and the CFile* result has member functions fp->GetFileName(); fp->GetFilePath(); cffung@myrealbox.com (CFF) wrote in message news:<2560187f.0408091936.1a1ed05b@posting.google.com>... >...

search macro with array
Hello. 3rd try, hope this post goes through. Using Excel X for Mac. Need a macro to search column Q for a list of stock ticker symbols for funds owned. When one is found, highlight that row and shade it light green. Thought I would make my first try at an array and cobbled together the macro below. It doesn't crash or return error messages but it also doesn't work. Stepping through it I noticed it dumps out of the Do loop after nine cycles and there are 9 fund names in the list (array). Could be a clue, but to what I don't know. Any help would be appreciated. Sub NLF...

export type error in report publishing
when i publish any report from GP to Business Portal then i recieved a message that "export type error" and when i see help for this error, help emphisis on installing PDF writer. can u tell me what is the right solution? ...

Serializing object graph directly to XML document rather than to text
Is there a way to serialize a graph of objects and get the output as an XML document, without first serializing to text and then parsing the text (I know how to do this but I find it really silly and inefficient). I googled around and from what I found, the answer is NO. Am I missing something obvious? Is there something new coming in .NET 2.0? Of course, I'm also interested in the reverse operation (deserializing directly from XmlDocument rather than from text). Bruno Bruno Jouhier wrote: > Is there a way to serialize a graph of objects and get the output as an XML > ...

IVAREC type of transaction
Does anyone know where these types of transactions originate from? It says a "GJ" and we cannot zoom back to the original. It definitely was NOT entered into the GL. It shows as being posted in late December, which posted into November, but all our modules for Novemeber were closed, so we need to find the hole that this mysterious transaction came from to prevent it from happening again. We do NOT use BOM. IVA indicates an Inventory Adjustment origination. RECON indicates a Reconciliation origination. I've never seen this journal reference before but I'd...

What are: "Control Source" , "Row Source" and "Row Source Type" ?
Dear experts, Kindly explain the following terms and functions in MS Access: "Control Source" "Row Source" "Row Source Type" "Column Count" "IME Hold" "IME Mode" Thanks a lot , experts ! -- Allen Phailat Wongakanit "ali" <ali@discussions.microsoft.com> wrote in message news:B2741CBC-BAB0-4DE1-8F00-FF04B1E21A7B@microsoft.com... > Dear experts, > > Kindly explain the following terms and functions in MS Access: > > "Control Source" The field which is the bound source of data for th...

why cant i see .csv as save file type
I am using excel 2003 and am trying to save a spreadsheet as a .csv file so i can export my hotmail contacts into gmail, any ideas why the option is not there? Manhy thanks On Mon, 18 Jul 2005 19:44:02 -0700, "Adie" wrote: >I am using excel 2003 and am trying to save a spreadsheet as a .csv file so >i can export my hotmail contacts into gmail, any ideas why the option is not >there? Manhy thanks Should be titled: CSV (Comma Separated Values) MP- -- "Learning is a behavior that results from consequences." B.F. Skinner available as CSV(comma delimited) in ...

PM Field
Hello, I am doing some work with PM30200, the Payables Paid Transaction History table. The table contains a field called CNTRLTYP (Control Type) that contains an integer. It appears to be used when say an invoice and an unrelated payment have the same voucher number. I believe that this happens when the voucher number and payment number are identical even though the transactions are not related, as when both numbering sequences have the same starting point, ie.. 000000001. It appears that a similar field, by the same name, is used in numerous tables throughout GP. Can anyone confirm my assu...

understanding use of xsi:type
I have a bit of xml that I am trying to create an xsd schema from. A very simplified version is as follows: <?xml version="1.0" encoding="UTF-8"?> <centre xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="java:ucles.cbtas.model.Centre"> <number>25279</number> <customer-id>16</customer-id> </centre> The real xml is much more complex but the basic problem is the same. If I use xsd.exe to create a schema from this I get the following: <?xml version="1.0" encoding="utf-8"...