Mapping XML with Schema to Entity in C# - c#

I am trying to find an article I read about a month ago. I the article the author talk about using the XML classes in .net to map xml with a schema to POCO objects and also showed how to create a schema straight from the objects that he had. This is exactly what I'm trying to do know, but all I seem to be able to find is articles talking about manually walking through the xml and extracting the values for your objects.
I know I can manually spin through the XML to get my objects, but I have several different objects I need to map, so I'd rather go down the automated route if there is one. Does anyone know how to build a schema from a .net object and then map XML files to it with some .net automagic?

The xsd.exe command-line utility is your friend!
See the MSDN docs for details on how to use it and what you can do with it.
In brief:
It can take a .NET assembly and generate XSD schema for each of the classes, or it can take an existing XML file and generate a XSD schema from it (as good as it can guess it), and then a C# or VB.NET class from that schema that allows you to easily deserialize a XML file into a .NET object directly.
There's also Xsd2Code - a Visual Studio (at least 2008 - not sure about 2010) plugin that allows you to have a XSD file in your project, and create a C# class from it in the Solution Explorer.

Related

How can I merge XML comments back into a .cs file?

Extracting comments out of C# class files is relatively easy (see Extracting doc comments from C# source file), but I've recently come into the opposite problem.
My project has a bunch of classes that are generated from XML schema (via Microsoft's xsd.exe). I'd like to write out XML documentation on these classes, but we have to recreate them every so often. I'd like to be able to write out the comments, extract them into their own .xml file, run xsd.exe to recreate the classes from the schema, and then merge the comments back in.
Is there some way to do this?
I peeked inside xsd.exe of the v8.1A version of the SDK (it was written in .NET so you can use a tool like JustDecompile to see what it does). The method which drives the XSD->C# generation is called ImportSchemasAsClasses. What it does is read the XSD files into a raw XmlSchemas instance, import the schemas with the XmlSchemaImporter class (into an abstract model called type mapping), then generate code with the XmlCodeExporter class into Code DOM classes. As you can see from the links, these are public, but undocumented API's. But you can easily replicate what xsd.exe does (you only need to call public .NET API's, just copy and paste what xsd.exe does) and tap into the right place to add some comments into the Code DOM, nice and clean, no string manipulations needed.

Create Intellisense from stored dynamic objects

Im about to create some settings for MVC projects and sites, based on dynamic variables etc.
These settings will be stored in xml for easy read and write.
My question now, after reading about extending the intellisense in this question:
Is it possible to provide intellisense for dynamic objects in visual studio?
Is if its possible to read my saved settings (which are stored at runtime) and then for the next run build a intellisense from that?
I.E. for each of these site.setings.layout.width a list of the "older" saved xml-defined defined dynamics will be able to show up?
If all you need is xml "intellisense" then consider designing xml schemas and dump them in Visual Studio installation Folder\xml\Schemas or include them in your solution and VS will do the rest if the namespaces match appropriately.
Edit:
Coming back to this after a while. No other answer appears to have been given so I'll try to be more creative.
Visual Studio has an option to generate an xsd from an xml file. Note that the schema will be mostly an approximation but it will match the file and will be a good description of structure. If you could find a way to call that from a command line (or possibly find a similar tool for the step) you can then chain that with xsd.exe and generate C# classes from it at build time (prebuild step)
If point one is too cumbersome you could try to write a T4 template that reads a previous configuration file and generates your custom code based on that. Generating a POCO property structure based on some xml should be fairly simple with T4. The template should be run as a precompiled step.
Note that both suggestions involve static code generation. A full dynamic solution could be done with F# type providers but that is not available for C#.

What is the best way to read and write cXML documents in C#?

I know this is a vague open ended question. I'm hoping to get some general direction.
I need to add cXML punchout to an ASP.NET C# site / application. This is replacing something that I wrote years ago in ColdFusion.
I'm a reasonably experienced C# developer but I haven't done much with XML. There seems to be lots of different options for processing XML in .NET.
Here's the open ended question: Assuming that I have an XML document in some form, eg a file or a string, what is the best way to read it into my code? I want to get the data and then query databases etc. The cXML document size and our traffic volumes are easily small enough so that loading the a cXML document into memory is not a problem.
Should I:
1) Manually build classes based on the dtd and use the XML Serializer?
2) Use a tool to generate classes. There are sample cXML files downloadable from Ariba.com.
I tried xsd.exe to generate an xsd and then xsd.exe /c to generate classes. When I try to deserialize I get errors because there seems to be "confusion" around whether some elements should be single values or arrays.
I tried the CodeXS online tool but that gives errors in it's log and errors if I try to deserialize a sample document.
2) Create a dataset and ReadXml()?
3) Create a typed dataset and ReadXml()?
4) Use Linq to XML. I often use Linq to Objects so I'm familiar with Linq in general but I'm struggling to see what it gives me in this situation.
5) Some other means.
I guess I need to improve my understanding of XML in general but even so ... am I missing some obvious way of doing this? In the old ColdFusion site I found a free component ("tag") which basically ignored any schema and read the XML into a "structure" which is essentially a series of nested hash tables which was then easy to read in code. That was probably quite sloppy but it worked.
I also need to generate XML files from my C# objects. Maybe Linq to XML will be good for that. I could start with a default "template" document and manipulate it before saving.
Thanks for any pointers ...
If you need to generate arbitrary XML in an exact format, you should generate it manually using LINQ-to-XML.

XSD.exe and "Circular Group references"

I am attempting to build some classes so that I can deserialise an XML file created by a third party application. Luckily the developer of the 3rd party application included a schema file with their code so that the XML file can be understood.
When I use the XSD.exe tool from Visual Studio the process fails reporting the following error
"Group 'SegGroupOrSegmentGrouping' from targetNamespace='' has invalid definition: Circular group reference."
Any help in how I can generate the class files in light of this error would be appreciated.
A copy of the schema file can be found here : schema file
Try using svcutil; it can handle the circular references.
In the following example, eExact-Schema.xsd is an XSD that xsd.exe cannot handle.
Example:
C:\SRC\Exact>svcutil eExact-Schema.xsd /language:C# /dataContractOnly /importxmltypes /out:exact.cs
This is always a good place to start; you can now use this class and alter to suit your style/needs, add comments, etc, and it will save you a lot of time/searching over doing it all from scratch.
I had this same problem recently,
I was given a Schema from a third party company who were returning an xml structure from a webservice. I then wanted to deserialise the response and store the information into a database with NHibernate.
No problem I thought I'll just use xsd.exe and I'll have my classes. Unfortunately this was not to be. Xsd.exe failed with exactly the same error you are getting. This is because it is unable to resolve circular references.
I spent a good few days looking at alternatives until in the end I wrote my own class structure to the schema and was able to deserialise perfectly. The answer here is to write your own C# classes and decorate them with the appropriate attributes.
Save yourself some time and heartache and don't continue to try and generate the classes you need automatically in the end although time consuming the classes you write won't make the compromises that most tools (which don't work perfectly) will make you make.
Took me about 3 days to write the class structure (it was large) but I ended up with a quality solution.
One thing is certain you will not be able to use xsd.exe and most other tools I tried after googling this either did not work properly or were buggy.
After trying several third party tools, I found that Liquid Technologies has a very robust generator called Liquid XML Data Binder 2012. It was able to handle the circular group reference problem I faced. It can generate code for just about any version of .net from 2.0 on. The classes it generates do depend on a redistributable dll that they provide. I'm using the trial version and I wouldn't be surprised if a purchase of the full version will be necessary before I go to release. However, having saved me probably a hundred hours or more of error prone hand coding, I can't complain.
The easiest method for me is to create the XSD file from the actual XML file with XSD.EXE. Then create a class from the new XSD file. You may be required to modify the class periodically if nodes or types are introduced that did not exist in the original XML but you will save yourself HOURS of coding time!!!!

Read XML into xsd.exe generated classes. Good idea?

I have a fairly complex XML coming my way and I have the XSD for it. I generated classes via xsd.exe and read XML into the class structure via the XmlSerializer described here.
It works great. However, this is the first time I've done it this way and I'll be reading in tons of XML files going forward from various sources. How reliable is this method? Could one say with certainty that if the XML file conforms to the XSD specification, that the XmlSerializer will be able to read it in just fine?
Short answer: it's better. This is exactly how MSfts web services work, so if what you described didn't work, any of the .NET consumers would fail, like when you add a reference to a web service in .NET or Silverlight.

Categories