0

Hai All i want to create an XML file with following format

<myFiles>
<name>myname</name>
<place>myplace</place>
<mydata>
    <today>1-1-2011</today>
    <time>1 PM</time>
    <driving>
       <car>audi</car>
       <bus>volvo</bus>
    </driving>
</mydata>
<mydata>
    <today>1-1-2011</today>
    <time>1 PM</time>
    <driving>
      <car>audi</car>
      <bus>volvo</bus>             
    </driving>
</mydata>
</myFiles>

For creating this i am using

class myfile
{
public string name {get;set;}
public string place {get;set;}
public list<mydata> mydata {get;set;}
}

then also public claa mydata { ...... } fro XML building i am using

static public void SerializeToXMLList(List<Movie> movies)
{
XmlSerializer serializer = new XmlSerializer(typeof(List<Movie>));
TextWriter textWriter = new StreamWriter(@"C:\movie.xml");
serializer.Serialize(textWriter, movies);
textWriter.Close();
}

But it will give me output like

<myFiles>
<name>myname</name>
<place>myplace</place>
<mydata>
   <mydata>
   <today>1-1-2011</today>
   <time>1 PM</time>
   <driving>
     <car>audi</car>
     <bus>volvo</bus>
   </driving>
   </mydata>
   <mydata>
   <today>1-1-2011</today>
   <time>1 PM</time>
   <driving>
      <car>audi</car>
      <bus>volvo</bus>
   </driving>
</mydata>
</mydata>
</myFiles>

so there was number of list with in mydata list with class name

How can i avoid that..., If any one knw pls help me..

4

2 回答 2

2

The reason for that is your have a property called 'mydata', and the objects within it are of type 'mydata'.

It's actually good practice to contain an array in an element like this so to be honest I think the layout you're getting is better, although you should probably choose a better name for the property, such as 'mydatacollection' or 'mydatalist'.

However, there's more information here on the attributes you can use to control the serialization: http://msdn.microsoft.com/en-us/library/2baksw0z%28v=vs.80%29.aspx#Y570

@Totero posted a link to another good question on this subject if you really do want to do this.

于 2012-06-12T08:37:25.720 回答
1

The reason it is creating nested containers is becuase you have an array mydata of mydata objects.

<mydata>
   <mydata>
   ....
   </mydata>
</mydata>

is the correct way of representing this. The quickest way to get the file in the exact format you want is to rename the array to something like "EraseTag". Open the XML file as a text file and remove all instances of "<EraseTag>".

However I want to reiterate the 2nd serialized example you gave is correct and as such can be reverted back to the object form by deserialization.

If you want to leave these tags out of the serialisation phase then you need to look at the following post:

XML Deserialization and Loose Array Items

and add a [Serializable] tag around your class.

于 2012-06-12T08:38:09.530 回答