C# Serialization with control over Attribute and Element without System.Serialization? - c#

I need to transform quickly some object into an XML string. If my project would not been in Silverlight, I would simply use the [Serializable] attribute with [XmlElement] and [XmlAttribute]. Unfortunately, this is not available in Silverlight. I can't use DataContract because it does not give the control of if the property need to be attribute or element tag.
So, what is my other option? I can do manually the XML using Linq-To-Xml but is there anything else more fast?

Another option is to use System.Xml.Serialization.XmlSerializer .

In terms of performance, XmlWriter (fast, non-cached, forward-only) with self-implemented serialization is preferable.

Related

What are these namespace properties doing?

I know this is pretty silly but just wondered if anyone had a link or knows exactly what this code is doing on my page?
namespace com.gvinet.EblAdapter.ebl
{
[Serializable]
[DesignerCategory("code")]
[GeneratedCode("System.Xml", "4.0.30319.225")]
[DebuggerStepThrough]
[XmlType(Namespace = "http://addresshere")]
public class TSAPassenger
{
then here is all of the strings for the form like name, address and such
I am thinking it is trying to grab the XML file that was created from the Database but just want to make sure.
It is not. These are all just metadata attributes.
Serializeable - Use the standard XmlSerializer to take public properties and fields and convert to XML for transport using no customization to the format (like ISerializable would). It is usually only used when going out of process (remoting, Web Services, WCF, etc)
DesignerCategory - This can be used a number of ways. This one tends to be used by the property grid in visual studio as a way to organize sections.
GeneratedCode - The application generated it for you, utilizing the System.Xml namespace in version 4.0.
DebuggerStepThrough - If you are stepping through code (F11), by default, skip over anything here (don't step into a property getting for example).
XmlType - Part of the serializer that allows you to provide a specific namespace that is generated in the output.
The items here do not actually get anything, just describe certain aspects of how something may be loaded/handled.
Hope that makes sense.
The Serializable and XmlType attributes are instructing the XML serializer that the class can be serialized and the schema to use when doing so.
XmlType Attribute
Serializable Attribute
DesignerCategory("code") Attribute
DebuggerStepThrough Attribute
These are attributes - used for declarative programming - you can find more about declarative programming online. But here is the link to .net attribute hierarchy page to get you started: http://msdn.microsoft.com/en-us/library/aa311259(VS.71).aspx
Also, these pages may be helpful:
What are attributes: What are attributes in .NET?
Attributes in C#: http://www.codeproject.com/Articles/2933/Attributes-in-C

stricter XmlSerializer which does not allow unused nodes

I generated C# classes based on XSD using the xsd.exe tool from the SDK. Then I can use that class to [de]serialize objects using XmlSerializer... However the serializer seems to be very forgiving.
Is it possible that I can make the serializer throw an exception in case there is missing property or a "strange" XML node?
I think one way is to modify the setter of the property and make it validate the data (or use XSD validation)... However is there any other alternative solution for this problem ?
You can implement the IXmlSerializable interface and in the ReadXml method implementation, check for the specific elements that you require, throwing exceptions when you don't find them (or setting whatever notification you need to).
If you want to use a schema for validation (to use the minOccurs and maxOccurs schema attributes, for example), then you can configure the XmlReader instance to validate against the schema by setting the Schemas property on the XmlReaderSettings class that you pass to the Create method (note there are overloads of Create which take a TextReader, etc.).

C# : xml serialization of nodes with cyclic links

I have a class Node something like this :
class Node {
IEnumerable<Node> inputs;
}
Which basicly defines a simple graph.
I want to serialize my graph to a human-readable form, so normally I'd say xml would be the way to go.
But XML wasn't made with cyclic dependencies in mind :)
So - what would be the best way to go for serialization of my graph ?
I can think of a few ways :
ditch XML, create my own format.
use XML, tag each node with a unique ID, store connection-lists separate from the Nodes and resolve after loading
But I think other people must have had this same problem before, so there might be some better options.
Does anyone know of a solid approach ?
For xml, I would go with the id approach (changing the DTO model such that it isn't cyclic).
Note that DataContractSerializer can support cyclic object graphs automatically by passing in true for the preserveObjectReferences option in the overloaded constructors; it won't be quite as simple as XmlSerializer output, but it will still be readable.
If you switch to WCF DataContractSerializer, you can preserve the Object References (in 3.5 SP 1 and later)
[DataContract(IsReference=true)]
Sowmy has a good write up here

Write CLR objects to XML with LINQ

I have an ObservableCollection items. I want to convert these to XML format so that I can store them for later use. I'm a little new to LINQ and I'm not sure how to do this. I know that I need to rely on the XDocument. But I'm not sure how to execute the query and get the results into a string format.
Can somebody please provide some pointers for me? It just seems like such an easy task, I'd be surprised if it couldn't be done.
Thank you,
You need Linq to XML. I can't post a real code here since I don't know the structure of your data, but here's a dummy example:
List<Person> people = ...
var doc = new XDocument(
new XElement("People",
from p in people
select new XElement("Person",
new XAttribute("Id", p.Id),
new XElement("LastName", p.LastName),
new XElement("FistName", p.FirstName))));
doc.Save("people.xml");
Note that Linq is not the only option here. Another very good approach is XML serialization.
Using the DataContractSerializer is your best bet. It's designed to do exactly what you are asking for.
http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractserializer(v=VS.95).aspx
Advantages over XMLSerializer:
Opt-in rather than opt-out properties to serialize. This mean you specify what you want serialize
Because it is opt in you can serialize not only properties, but also fields. You can even serialize non-public members such as private or protected members. And you dont need a set on a property either (however without a setter you can serialize, but not deserialize)
Is about 10% faster than XmlSerializer to serialize the data because since you don’t have full control over how it is serialize, there is a lot that can be done to optimize the serialization/deserialization process.
Can understand the SerializableAttribute and know that it needs to be serialized
More options and control over KnownTypes
Disadvantages:
No control over how the object is serialized outside of setting the name and the order
I'm not sure what you want.
You can create a XElement and convert it to a string with the ToString method.
You can do the same with XDocument.
I'm not at all familiar with Silverlight, but it sounds like you are going to need to use XML serialization. XML serialization allows you to serialize an object into an XML representation, which you can then later deserialize from XML back into an object.
Here are some tutorials and information on XML serialization in .NET:
XML Serialization
XML Serialization Using C#
XmlSerializer class

Creating something similar to System.ServiceModel.Syndication using .NET 3.5

If I am dealing with several standard xml formats what would be the best practice way of encapsulating them in C# 3.5? I'd like to end up with something similar to the System.ServiceModel.Syndication namespace.
A class that encapsulates the ADF 1.0 XML standard would be one example. It has the main XML root node, 6 child elements, 4 of which are required IIRC, several required and optional elements and attributes further down the tree. I'd like the class to create, at a minimum, the XML for all the required pieces all the way up to a full XML representation. (Make sense).
With LINQ 4 XML and extension classes, etc, etc, there has to be some ideas on quickly generating a class structure for use. Yes? No? :)
Am not sure if I gave enough details to get one correct answer but am willing to entertain ideas right now.
TIA
XML serialization seems a good approach. You could even use xsd.exe to generate the classes automatically...
EDIT
Note that the class names generated by the tool are usually not very convenient, so you might want to rename them. You might also want to change arrays of T to List<T>, so that you can easily add items where needed.
Assuming the class for the root element is named ADF, you can load an ADF document as follows :
ADF adf = null;
XmlSerializer xs = new XmlSerializer(typeof(ADF));
using (XmlReader reader = XmlReader.Create(fileName))
{
adf = (ADF)xs.Deserialize(reader);
}
And to save it :
ADF adf = ...; // create or modify your document
...
XmlSerializer xs = new XmlSerializer(typeof(ADF));
using (XmlWriter writer = XmlWriter.Create(fileName))
{
xs.Serialize(writer, adf);
}
Why not just follow the pattern of the SyndicationFeed object in the Syndication namespace? Create a class that takes in a Uri to the xml document or just takes in the document fragment.
Then parse the document based on your standards (this parsing can be done using LinqToXml if you wanted to, though regEx might be faster if you are comfortable with them). Throw exceptions or track errors appropriately when the document doesn't pass the specification rules.
If the document passes the parse step then break the pieces of the document out into public getter properties of your object. Then return the fully hydrated object back to the consumer for use
Seems pretty straight forward to me. Is that what you are after or are you looking for something more than this?

Categories