tags:

views:

76

answers:

2

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

A: 

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?

Foovanadil
-1: you can't use regex to parse XML, in general.
John Saunders
yep, regex are definitely a bad idea for that kind of things... anyway, .NET provides plenty of support for reading XML
Thomas Levesque
A: 

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);
}
Thomas Levesque
Cool tool, thanks. I've generated my classes and am now trying to figure out the correct way to use them. Any samples handy?
Keith Barrows
See my edit, I added code samples
Thomas Levesque
Thanks! I'll play with this but it seems to answer my question.
Keith Barrows