How to prevent object to be serialize in XML - c#

IDE: VS, C# .net 4.0, winforms
With the help of XMLSerializer I am able to generate XML of C# object, but I want to remove specific objects.
Is there any way to prevent specific objects to prevent in XML..?
using (MemoryStream xmlStream = new MemoryStream())
{
/*
XmlSerializer.Serialize Method (XmlWriter, Object)
Serializes the specified Object and writes the XML document to a file using the specified xmlwriter
Parameters
xmlWriter-
Type: System.Xml.XmlWriter
The XmlWriter used to write the XML document.
Type: System.Object
The Object to serialize.
*/
xmlSerializer.Serialize(xmlStream, YourClassObject);
xmlStream.Position = 0;
//Loads the XML document from the specified string.
xmlDoc.Load(xmlStream);
string fileName = YourClassObject.GetType().Name;
xmlDoc.Save("C:\\Users\\Yogesh\\Desktop\\Yardz_XMLS\\" + fileName + ".xml");
return xmlDoc.InnerXml;
Is there any way to prevent some properties to be serialize..?

Put XmlIgnore attribute on properties that you don't what to be serialized:
public class YourClass
{
public string Serailized { get; set; }
[XmlIgnore]
public string NotSerialized { get; set; }
}
See "Controlling XML Serialization Using Attributes" for more information.

Related

C# Xml Serializable enum type

I want to load a XML file with XML serialization. The type now should be an enum type.
So the XML looks like this:
<Ressource name="ressource_name" type= "Integer" >
...
</Ressource>
And I wanted to load it into a class like this:
[Serializable]
public enum Res_Type
{
[XmlEnum(Name = "Integer")]
Integer,
[XmlEnum(Name = "Decimal")]
Decimal,
[XmlEnum(Name = "Text")]
Text
}
public class Ressource
{
[XmlAttribute]
public string name { set; get; }
[XmlAttribute]
public Res_Type type { get; set; }
}
When I search for this topic I only find different ways of solving it, then I need it to. I need to have the XML like shown above, but I have no idea how to load the information in type as an enum.
Update:
To test the serialization and the deserialization I am using this code:
Ressource res = new Ressource();
res.name = "ressource_name";
res.type = Res_Type.Integer;
XmlSerializer serializer = new XmlSerializer(res.GetType());
using (StreamWriter writer = new StreamWriter(#"h:\test.xml"))
{
serializer.Serialize(writer, res);
}
XmlSerializer xmlSerializer = new XmlSerializer(typeof(Ressource));
StringReader stringReader = new StringReader(#"h:\test.xml");
res = (Ressource)xmlSerializer.Deserialize(stringReader);
And I am getting the error: InvalidOperationException
Your problem is that you are using a StringReader rather than a StreamReader:
StringReader stringReader = new StringReader(#"h:\test.xml");
This means that your code is attempting to deserialize the contents of the string literal #"h:\test.xml" itself rather than the file to which it refers. This of course fails because the string h:\test.xml is not even well-formed XML.
Instead you should do:
var fileName = #"h:\test.xml";
// Write the file as before
using (var reader = new StreamReader(fileName))
{
res = (Ressource)xmlSerializer.Deserialize(reader);
}
Working .Net fiddle here.

C# Writing list of objects into file (easiest way) [duplicate]

This question already has answers here:
How to save/restore serializable object to/from file?
(6 answers)
Closed 4 years ago.
I've got a class of payments:
class Payments
{
public string id; //it must be string because of a method
public string name;
public int payment;
}
And a list of objects:
private List<Payments> database = new List<Payments>();
The question is:
How can I write it in a file (which is located in the solution's folder) in the easiest way? It shouldn't be the most efficient.
You can use Newtonsoft json to easily serialize this list of objects into json and write that to a file,
using (StreamWriter file = File.CreateText(#"f:\payments.json"))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(file, database);
}
mark your class with [Serializable] attribute and use generic build in serializer class.
You can use it like this
public static void Serialize<T>(T objectToSerialize, string path)
where T : class
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (var writer = new StreamWriter(path))
{
serializer.Serialize(writer, objectToSerialize);
}
}
where T is your Payments class and path is your destination path.
In this approach you will serialize it to xml structure, you can easily swap it into binary structure, by using other serializer class. As long as only public properties will by serialized you need to replace your public fields with public properties with public get set accessors.

Convert xls file to xml file using c#

I am a newbie in c#, i have to convert an excel file to an xml with simple nodes. I have done it so far with interop. I have written parts of code to open an xls , close an xls, get value of a cell by Get_range method, and release the object.
But, now i have to output an xml file, i have to goto a particular cell and print a node and a value of a cell. It can be a simple plain text also which i can output or we can use the linq Xelement and Xattributes as well. I think when using get_range:
xlWorkSheet.get_Range("B3", "B3").Value2
i need to print the same in excel.
I am not sure how to do this, please guide me. The resulting xml should look something like this:
<WpData>
<WpType>Design</WpType>
<ReviewType>half</ReviewType>
<References>[1] https:///SysService/SysService_AsrDet/trunk/_doc/20_Design
</References>
<Author>deh</Author>
<Reviewer>abc</Reviewer>
</WpData>
thanks in advance.
You searching for xml serialization. You should define class like this:
[Serializable]
public class WpData
{
public string WpType { get; set; }
public string ReviewType { get; set; }
public string References { get; set; }
public string Author { get; set; }
public string Reviewer { get; set; }
}
Note Serializable attribute on class.
Then you should fill your object from excel data and use XmlSerializer:
WpData xmlSerializibleObject = new WpData();
//....
//here you should fill it from excel based on your data
//And then you can just serialize it to string
string xmlString;
XmlSerializer xmlSerializer = new XmlSerializer(xmlSerializibleObject.GetType());
using(StringWriter textWriter = new StringWriter())
{
xmlSerializer.Serialize(textWriter, xmlSerializibleObject);
xmlString = textWriter.ToString();
}
xmlString will have xml that you need is you fill your object correct from excel.

How would I deserialize some class from XML (file), and vice versa?

I have the following class and data members (plus irrelevant methods) I am new to XML and .NET (that excuse is getting old though) and have spent a couple of days reading the MSDN entries (and whatever google turned up) for first XMLReader, then XMLDocument and now XDocument, XElement and XNode but am no closer to a concrete solution to serializing my class (perhaps I need to study serialization in .NET in more depth). To get me started I have some data in an XML file that I want to read (although it prolly is in the wrong format) in to initialize a class to initialize my application. The configuration class is as follows:
class IWantToFile
{
class DirsAndFiles
{
public List<string> Suffixes;
public string Dir;
}
enum OPOptsEnum
{
op1Description, op2Description, op3Description, op4Description,
op5Description, op6Description, op7Description, op8Description,
};
List<DirsAndFiles> ProjectDirs;
bool[] OPOpts = new bool[(int)OPOptsEnum.op8Description + 1];
bool otherOpt;
}
Observing the one to one and one to many relationships therein (eg List<DirsAndFiles> ProjectDirs) can someone please give concise methods to read and write this data to a file? It would greatly assist my development in these fields.
I've got as far as:
if (File.Exists(SPECFILENAME)) {
XDocument xdoc = XDocument.Load(SPECFILENAME);
//Ummm.....
}
but then my lack of .NET XML and Linq exeperience fail me.
I think you might want to use the XmlSerializer, which 'Serializes and deserializes objects into and from XML documents'?
See How to serialize an object to XML by using Visual C# for sample code.
[Serializable]
public class MyObject
{
public string SerializeMe { get; set; }
[XmlIgnore]
public string DONTSerializeMe { get; set; }
}
Helper....
public static class SerializerHelper<T>
{
public static string Serialize(T myobject)
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
StringWriter stringWriter = new StringWriter();
xmlSerializer.Serialize(stringWriter, myobject);
string xml = stringWriter.ToString();
return xml;
}
public static T Deserialize(string xml)
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
StringReader stringReader = new StringReader(xml);
return (T)xmlSerializer.Deserialize(stringReader);
}
}
Usage
MyObject myObject = new MyObject();
string xml = SerializerHelper<MyObject>.Serialize(myObject);
MyObject DeserializedObject = SerializerHelper<MyObject>.Deserialize(xml);

Capture serialised XML when deserialising

.net, C#
Is it easily possible (by use of attributes etc) to automatically save the entire XML string (as a string field) that was created when an object was serialised when that object is deserialised?
I ask because I'm receiving an XML stub from a web service, and that stub contains a digital signature that I can use to verify the XML. I can deserialise the XML into a useful object that can be passed down into my application layer for verification, but I need the XML too. Ideally my new object would have an OriginalXML property or something. I could verify the XML at a higher level but it's not so convenient for me.
Cheers,
Chris.
You can load the XML file into a string, no problem. But the OriginalXML property would have to be marked with the [NonSerialized] attribute, because you don't want to store that string when you serialize. You'll have to deserialize, reload as an XmlDocument, and store the resulting string to that property.
XmlDocument xmlDoc = new XmlDocument();
try {
xmlDoc.Load(serializedFile);
}
catch (XmlException exc) {
// Handle the error
}
StringWriter stringWriter = new StringWriter();
XmlTextWriter xmlWriter= new XmlTextWriter(stringWriter);
xmlDoc.WriteTo(xmlWriter);
myObject.OriginalXML = xmlWriter.ToString();
HTH,
James
How about
[DataContract]
class FooBar
{
//this property doesn't have the DataMember attribure
//and thus won't be serialized
public string OriginalXml { get; set; }
[DataMember] private int _foo;
[DataMember] private string _bar;
static public FooBar Deserialize(XmlReader reader)
{
var fooBar =
(FooBar)new DataContractSerializer(typeof(FooBar)).ReadObject(reader);
fooBar.OriginalXml = reader.ToString();
return fooBar;
}
}

Categories