开发者

How to serialize large number of objects with provided xsd schema?

I have large collection of objects that I need to transform into xml that must validate against given XSD.

Class structure is not very complex (aobut twenty properties and two lists of child classes) i.e:

public class Person
{
   public string Street, Town, City, PostCode etc;
   public double Income, Tax, etc.;
   public List<Account> Accounts;
   ...
}

but the expected xml output complex and does not match class structure

<Person>
  <Address>
    <Street/><Town/><City/>
  </Address>
  <FinancialData>
    <Income/><Tax/>
  </Fin开发者_运维百科ancialData>
  <Accounts>
  <Account>
    <No>1</No>
    ...
  </Accounts>
</Person>

What's the best way to do that?

I tried to make XElement structure for each object and then combine them into XDocument and save

XElement document = new XElement("Person",               
   new XElement("Address",
      new XElement("Street", this.Street),
      new XElement("City", this.City),
   new XElement("FinancialData",
      new XElement("Income", this.Income), ...

but process of creating XElements is very slow and with 200 objects it takes couple minutes wheras I need to serialize 50.000 objects.

I thought about XmlSerializer but class and xsd don't match.

UPDATE: I created custom classes that I map my base class to it. Then using XmlSerializer and its attributes I serialize my objects in xml. It's pretty fast.


I think you might want to consider using a template engine of your choice, for example NHaml. First you have to create an XML template which conforms to your schema, then you use a template engine to render the template using your actual data.

In the case of NHaml it will look approximately like this:

%Person
  %Address
     %Street = person.Street
     %Town = person.Town
     %City = person.City
  ...
  %FinancialData
  - foreach (var account in person.Accounts)
    %Account
      %No
        = account.No
      ...


Well, this XDocument (Linq2Xml) would be simple but...

How about an old DataSet? There are 2 ways:

  1. Generate in Visual Studio:

    • Add xsd to C# project.
    • Open the file from Solution Explorer "Open with", select DataSet Editor..yes yes...
    • Click the DataSet and go to properties
    • Set name to [your_class] and set Custom Tool to MSDataSetGenerator
    • Now, VS will generate the code behind. Then you can use the generated class in the code.
  2. Or, From Start menu -> Visual Studio -> Visual Studio Tools -> Visual Studio Commend Prompt has XSD.EXE which can be used to generate the class.


If you want to use XmlSerializer you can make an XslCompiledTransform to convert an xml document from one format to another with xsl stylesheet.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜