I have a myXML.xml file.
I used xsd.exe to generate and myXMLClass.cs class files which contains many partial classes.
Now, I want to use this myXMLClass.cs class and retrieve all the nodes/attributes/values/data using my original myXML.XML file. But, how can I do this because of myXMLClass.cs has so many partial classes?
eg. I want to do deserializing using TypeOf myXMLClass like like this. But, myXMLClass contains many partial classes.
XmlSerializer serializer = new XmlSerializer(typeof(myXMLClass??));
Thank you
Update:
Also, I am having problem with obtaining the "code" and "description" of this tag that has this kind of setup.
<HitCode code="4" description="CONSUMER DECLARATION" />
Again, my goal is to retrieve "code" and "description" of this tage.
I ended up ditching the XSD.EXE generated .CS class.
I decided to make my own object class which resemble the XML schema and it works.
#Seminda Thank you for the suggestion.
Related
I have an auto generated c# class file from an xml schema using the xsd generator tool.
There is a property in this class that i need to rename from "Balance" to "balance" when the xml file gets created.
As this is a generated class i need to update the created xml object on the fly before seralizing so cant just add an atrribute over the class property with the expected name.
I have accomplished the task of ignoring certain properties by using the XmlAttributes class so am sure there is something i could do along same lines for this
Can anyone point me in the direction of how to achieve this?
Thanks
I have managed to resolve my issue by using the following:
var overrides = new XmlAttributeOverrides();
overrides.Add(typeof(MyGeneratedCustomType), "Balance", new XmlAttributes { XmlAttribute = new XmlAttributeAttribute("balance") });
var serializer = new XmlSerializer(xmlFile.GetType(), overrides);
MyGeneratedCustomType is a type that appears in the generated xsd class which holds the property i needed to rename. Its an elegant solution as there is very minimal code required.
Assuming you need to deserialize from XML like this:
<root>
<Balance />
</root>
and then serialize to XML like this:
<root>
<balance />
</root>
You have two options here:
You could just create a second class that mirrors your auto-generated class in every way except for having [XmlElement("balance")] on the Balance property in the mirrored class. If the generated class is XsdGenerated and the mirrored class is CustomClass, create a constructor or override the =s operator to be able to populate the CustomClass with all the fields from XsdGenerated. When you serialize CustomClass, you should get the desired result. I think this is the preferable option.
Implement IXmlSerializable on XsdGenerated. Call base() in the ReadXml method, and just have the WriteXml method create the balance tag in lower case. Note that this option is probably more challenging to write/maintain and would limit your ability to serialize and deserialize - it'd be a one way operation, unless you created an even more complex mechanism to set whether ReadXml() and WriteXml() should treat balance with an upper or lower case b.
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
Using the xsd.exe tool, class are generate from a xsd file.
I would like to change the name of a root element put I can not since the XmlRootElementAttribute can not be duplicate. So idealy I would like that the xsd tool generate a partial classe like this:
...
[System.Xml.Serialization.XmlRootAttribute(ElementName="Request", IsNullable=false)]
public partial class SendMessage { ... }
But I have no clue how to change the ElementName propertie.
Thanks
I take your XSD defines an element SendMessage, and you want the annotation to be something else, Request in your case.
Short answer is no, it cannot be done with XSD.exe alone; the tool doesn't allow a syntax where one can customize the name of the generated classes.
Which brings in the long version of the answer... The annotations always reflect what the XML is. If you change the ElementName value, then your generated XML will be different. If you want the XML different, then you should change the schema file instead.
This is the kind of question that needs a lot of explaining as to why would one want this... in order to get a positive answer, as in "yes, this is how achieve the why".
I am creating an XML file which is based upon the Atom 1.0 specification. The .net Syndication classes are ideal for producing the Atom elements of my document but I need to extend this class so that I can create my own elements like below using strongly types C# classes. What is the best way to extend these classes so to get my desired results?
<myNS: userdata myNS:field=”first_name” >Fred Bloggs</myNS:userdata>
I have tried to create my own Feed and Item by inheriting from SyndicationFeed and SyndicationItem respectively but this means I will have to create my own feedFormatter class as the Atom10FeedFormatter class only takes SyndicationItems as parameters. I think I am going to have to create the following classes to get my desired result but wanted to put it to the community to see if its the correct way to go an if anybody else has done anything similar.
MyFeedFormatter : Atom10FeedFormatter
MyFeed : SyndicationFeed
MyItem : SyndicationItem
The .NET Syndication Feed supports extensions. It's possible through SyndicationFeed.ElementExtensions and SyndicationFeed.AttributeExtensions.
http://msdn.microsoft.com/en-us/library/system.servicemodel.syndication.syndicationfeed.elementextensions.aspx
I started off doing it this way but I need a way and even created some Extension Methods but I need to make the whole document creation process type safe.
Therefore I have created elements as objects (see below) which have public properties as there attributes. By just using the extensions I am leaving it open to errors if fields are incorrectly spelt etc and thus not having a valid XML doc.
myItem.userdata = new UserDataElement
{
Field = “first_name”,
Content = "Fred Bloggs"
};
So I have xml that looks like this:
<todo-list>
<id type="integer">#{id}</id>
<name>#{name}</name>
<description>#{description}</description>
<project-id type="integer">#{project_id}</project-id>
<milestone-id type="integer">#{milestone_id}</milestone-id>
<position type="integer">#{position}</position>
<!-- if user can see private lists -->
<private type="boolean">#{private}</private>
<!-- if the account supports time tracking -->
<tracked type="boolean">#{tracked}</tracked>
<!-- if todo-items are included in the response -->
<todo-items type="array">
<todo-item>
...
</todo-item>
<todo-item>
...
</todo-item>
...
</todo-items>
</todo-list>
How would I go about using .NET's serialization library to deserialize this into C# objects?
Currently I'm using reflection and I map between the xml and my objects using the naming conventions.
Create a class for each element that has a property for each element and a List or Array of objects (use the created one) for each child element. Then call System.Xml.Serialization.XmlSerializer.Deserialize on the string and cast the result as your object. Use the System.Xml.Serialization attributes to make adjustments, like to map the element to your ToDoList class, use the XmlElement("todo-list") attribute.
A shourtcut is to load your XML into Visual Studio, click the "Infer Schema" button and run "xsd.exe /c schema.xsd" to generate the classes. xsd.exe is in the tools folder. Then go through the generated code and make adjustments, such as changing shorts to ints where appropriate.
Boils down to using xsd.exe from tools in VS:
xsd.exe "%xsdFile%" /c /out:"%outDirectory%" /l:"%language%"
Then load it with reader and deserializer:
public GeneratedClassFromXSD GetObjectFromXML()
{
var settings = new XmlReaderSettings();
var obj = new GeneratedClassFromXSD();
var reader = XmlReader.Create(urlToService, settings);
var serializer = new System.Xml.Serialization.XmlSerializer(typeof(GeneratedClassFromXSD));
obj = (GeneratedClassFromXSD)serializer.Deserialize(reader);
reader.Close();
return obj;
}
Deserialize any object, as long as the type T is marked Serializable:
function T Deserialize<T>(string serializedResults)
{
var serializer = new XmlSerializer(typeof(T));
using (var stringReader = new StringReader(serializedResults))
return (T)serializer.Deserialize(stringReader);
}
Well, you'd have to have classes in your assembly that match, roughly, the XML (property called Private, a collection property called ToDo, etc).
The problem is that the XML has elements that are invalid for class names. So you'd have to implement IXmlSerializable in these classes to control how they are serialized to and from XML. You might be able to get away with using some of the xml serialization specific attributes as well, but that depends on your xml's schema.
That's a step above using reflection, but it might not be exactly what you're hoping for.
Checkout http://xsd2code.codeplex.com/
Xsd2Code is a CSharp or Visual Basic Business Entity class Generator from XSD schema.
There are a couple different options.
Visual Studio includes a command line program called xsd.exe. You use that program to create a schema document, and use the program again on the schema document to creates classes you can use with system.xml.serialization.xmlserializer
You might just be able to call Dataset.ReadXml() on it.
i had the same questions few years back that how abt mapping xml to C# classes or creating C# classes which are mapped to our XMLs, jst like we do in entity Framework (we map tables to C# classes). I created a framework finally, which can create C# classes out of your XML and these classes can be used to read/write your xml. Have a look