简体   繁体   中英

XML Serialize C#

I'm using

List<EFacebook> facebooks = BFacebook.ReadFacebookFriends(user.EProviders
    .Where(i => i.ProviderType == EProvider.EnumProviderType.Facebook)
    .First().Token);

StringBuilder xml = new StringBuilder();
foreach (EFacebook i in facebooks)
{
   xml.AppendFormat("<id>{0}</id>", i.id);
}

Can anybody suggest a better code to serialize each i.id into an XML string?

Edit: The facebook object has close to 20 properties. If I XmlSerializer all 20 properties are serialized into the XML. I just need the id column.

You might want to take a look at XML Serialization already built into the .NET Framework.

You can use code similar to the following to serialize the object:

MySerializableClass myObject = new MySerializableClass();
// Insert code to set properties and fields of the object.
XmlSerializer mySerializer = new 
XmlSerializer(typeof(MySerializableClass));
// To write to a file, create a StreamWriter object.
StreamWriter myWriter = new StreamWriter("myFileName.xml");
mySerializer.Serialize(myWriter, myObject);
myWriter.Close();

See: How to serialize

You can flag properties to be ignored using the XmlIgnore attribute as shown below:

public class Group
{
   // The XmlSerializer ignores this field.
   [XmlIgnore]
   public string Comment;

   // The XmlSerializer serializes this field.
   public string GroupName;
}

See XMLIgnore

XmlSerializer xs = new XmlSerializer(typeof(int[]));
xs.Serialize(stream,facebooks.Select(x=>x.id).ToArray())

I would use Linq To Xml to create the Xml Tree structure

See for an example: Linq To Xml

If you're just saving the id values into an xml string then I wouldn't say that you're 'serializing' the objects.

Whenever working with XML it's much nicer to use an XML library than to wrangle with text. One obvious reason is that it guarantees your XML will be well-formed.

I'd do something like this:

List<EFacebook> facebooks = GetFriends();
var facebookIds = facebooks.Select(f => new XElement("id", f.id));
var facebookXml = new XElement("facebookIds", facebookIds);

Which will give you XML like

<facebookIds>
  <id>1</id>
  <id>2</id>
</facebookIds>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM