I have the following situation:
4 methods that return XML
Have to create one big XML with these 4 XML pieces on an array
A small example of this would be the following:
<garage>
<owner>daniel</owner>
<cars>
<XmlElement>
<plate>ABC123</plate>
</XmlElement>
<XmlElement>
<plate>DSC563</plate>
</XmlElement>
<XmlElement>
<plate>AIO789</plate>
</XmlElement>
<XmlElement>
<plate>IUE692</plate>
</XmlElement>
</cars>
</garage>
I have an array of plate and want to inject that on the car which is an System.Xml.XmlElement[]
The problem is, I can't seem to find a way to get rid of the XmlElement element wrapping my objects, I just wanted it to be like:
<garage>
<owner>
<name>daniel</name>
</owner>
<cars>
<plate>ABC123</plate>
<plate>DSC563</plate>
<plate>AIO789</plate>
<plate>IUE692</plate>
</cars>
</garage>
I've tried playing around with the Xml Attributes but couldn't get exactly what I wanted.
Can someone please give me a hand?
here's the working code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using Xunit;
using Xunit.Abstractions;
namespace TestsProjec.XML
{
public class Tests
{
private readonly ITestOutputHelper _testOutputHelper;
public Tests(ITestOutputHelper testOutputHelper)
{
_testOutputHelper = testOutputHelper;
}
[Fact]
public void InjectingXml()
{
var serializer = new XmlSerializer(typeof(Garage));
var cars = new List<XmlElement>();
cars.Add(StringToXmlElement("<plate>ABC123</plate>"));
cars.Add(StringToXmlElement("<plate>DSC563</plate>"));
cars.Add(StringToXmlElement("<plate>AIO789</plate>"));
cars.Add(StringToXmlElement("<plate>IUE692</plate>"));
string fullXml;
var entity = new Garage()
{
owner = "Daniel",
cars = cars.ToArray()
};
using (MemoryStream ms = new MemoryStream())
{
using (XmlWriter tw = XmlWriter.Create(ms))
{
serializer.Serialize(tw, entity);
try
{
byte[] tmp = new byte[ms.Length - 3];
ms.Position = 3; //to skip the UTF-8 preamble
ms.Read(tmp, 0, (int)ms.Length - 3);
fullXml = Encoding.UTF8.GetString(tmp);
}
catch
{
fullXml = null;
}
}
}
_testOutputHelper.WriteLine(fullXml);
}
public XmlElement StringToXmlElement(string xml)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
return doc.DocumentElement;
}
}
public class Garage
{
public string owner { get; set; }
public System.Xml.XmlElement[] cars { get; set; }
}
}
If you use XElement, instead of XmlElement, you could get output you want, with XmlAnyElement Attribute:
public class Garage
{
public string owner { get; set; }
[XmlAnyElement]
public XElement[] cars { get; set; }
}
Your method StringToXmlElement will look like:
public XElement StringToXmlElement(string xml)
{
return XElement.Parse(xml);
}
An option is to use XmlSerializer and have class that represent your xml
class Program
{
static void Main(string[] args)
{
XmlSerializer serializer = new XmlSerializer(typeof(Garage));
var garage = new Garage
{
Owner = new Owner { Name = "Daniel" },
Cars = new List<string>
{
"ABC123",
"DSC563",
"AIO789",
"IUE692",
}
};
serializer.Serialize(File.Create("file.xml"), garage);
}
}
[Serializable]
public class Garage
{
[XmlElement("Owner")]
public Owner Owner;
[XmlArrayItem("Plate")]
public List<string> Cars;
}
[Serializable]
public class Owner
{
[XmlElement("Name")]
public string Name;
}
Related
I have one XML file called VehicleInfo.
I want to deserialize VehicleInfo in List of Vehicle.
Now I have one base class called Vehicle and three derived class named as Car, Bike, Truck.
How to deserialize specific object of vehicle based on value of Vehicle node in xml.
(ex. if node value is Car than object of car should be stored in List of vehicle)
<Vehicles>
<Vehicle>Car</Vehicle>
<Vehicle>Bike</Vehicle>
<Vehicle>Truck</Vehicle>
</Vehicles>
For example,
VehicleList class :
public class VehicleList
{
List<Vehicle> lstVehicles = new List<Vehicle>();
}
Vehicle class :
public class Vehicle
{
public string name = "Vehicle";
}
Car class :
public class Car : Vehicle
{
public Car()
{
name = "Car";
}
}
Bike class :
public class Bike : Vehicle
{
public Bike()
{
name = "Bike";
}
}
Truck class :
public class Truck : Vehicle
{
public Truck()
{
name = "Truck";
}
}
This Vehicle program is just example,
So, How can I deserialize specific object (Such as Car, Bike, or Truck) in List of Vehicle in VehicleList class based on value of node Vehicle.
Here is code and results to serialize. XML you cannot have an array as a root element. So in this case it make sense to have two classes : Vehicles and Vehicle. See code below :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
namespace ConsoleApplication107
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
Vehicles vehicles = new Vehicles()
{
vehicles = new List<Vehicle>() {
new Car() { make = "BMW"},
new Bike() { make = "Buffalo"},
new Truck() { make = "MAC"}
}
};
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
XmlWriter writer = XmlWriter.Create(FILENAME, settings);
XmlSerializer serializer = new XmlSerializer(typeof(Vehicles));
serializer.Serialize(writer, vehicles);
}
}
public class Vehicles
{
[XmlElement("Vehicle")]
public List<Vehicle> vehicles { get; set; }
}
[XmlInclude(typeof(Car))]
[XmlInclude(typeof(Bike))]
[XmlInclude(typeof(Truck))]
public class Vehicle
{
public string make { get; set; }
}
public class Car : Vehicle
{
}
public class Bike : Vehicle
{
}
public class Truck : Vehicle
{
}
}
Here is results :
<?xml version="1.0" encoding="utf-8"?>
<Vehicles xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Vehicle xsi:type="Car">
<make>BMW</make>
</Vehicle>
<Vehicle xsi:type="Bike">
<make>Buffalo</make>
</Vehicle>
<Vehicle xsi:type="Truck">
<make>MAC</make>
</Vehicle>
</Vehicles>
XmlSerializer supports some kinds of inheritance modelling, but: it is based on the elements/attributes, not the actual values; I'm not aware of any API that would support what you want from that data, so you'll have to deserialize them as strings, and post-process them to what you want.
An example of something that would be possible is:
<Vehicles>
<Car>...car things...</Car>
<Bike>...bike things...</Bike>
<Truck>...truck things...</Truck>
</Vehicles>
which can be achieved via:
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
[XmlInclude(typeof(Car))] // technically you only need XmlInclude
[XmlInclude(typeof(Bike))] // if you're using xsi:type resolution
[XmlInclude(typeof(Truck))] // but... it doesn't hurt us here
public abstract class Vehicle { }
public class Car : Vehicle { }
public class Truck : Vehicle { }
public class Bike : Vehicle { }
[XmlRoot("Vehicles")]
public class MyRoot
{
[XmlElement("Car", Type = typeof(Car))]
[XmlElement("Truck", Type = typeof(Truck))]
[XmlElement("Bike", Type = typeof(Bike))]
public List<Vehicle> Items { get; } = new List<Vehicle>();
}
static class P
{
static void Main()
{
var root = new MyRoot
{
Items =
{
new Car(),
new Bike(),
new Truck(),
}
};
var ser = new XmlSerializer(typeof(MyRoot));
var ns = new XmlSerializerNamespaces();
ns.Add("", "");
ser.Serialize(Console.Out, root, ns);
}
}
Ok, this is going to be long...
You can play with this solution .net-fiddle-here
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml.Serialization;
public class Program
{
public static void Main()
{
var root = new Vehicles
{
Items =
{
new Vehicle() { Name = "Car"},
new Vehicle() { Name = "Truck"},
new Vehicle() { Name = "Bike"}
}
};
var xmlSerializer = new XmlSerializer(typeof(Vehicles));
var memoryStream = new MemoryStream();
TextWriter stringWriter = new StreamWriter(memoryStream, System.Text.Encoding.UTF8);
xmlSerializer.Serialize(stringWriter, root);
string xml = System.Text.Encoding.UTF8.GetString(memoryStream.ToArray());
//Make XML
var obj = root;
var xmlString = obj.XmlSerializeToString();
//Make Object with Direct Deserialization
var vehicles = xmlString.XmlDeserializeFromString<Vehicles>();
//Make polymorphic object from generic vehicles with some "logic"
var polymorphicVehicles = new List<Vehicle>(); // ****** THIS is the collection you requested!!!! *********
// itterate all vehicles
foreach (var item in vehicles.Items)
{
// use json serialization, because casting Parent to Child is not acceptable
var jsonVehicle = JsonConvert.SerializeObject(item);
// depending on the Name of the vehicle, create a corresponding object
switch (item.Name)
{
case "Car":
var aCar = JsonConvert.DeserializeObject<Car>(jsonVehicle);
polymorphicVehicles.Add(aCar);
break;
case "Truck":
var aTruck = JsonConvert.DeserializeObject<Truck>(jsonVehicle);
polymorphicVehicles.Add(aTruck);
break;
case "Bike":
var aBike = JsonConvert.DeserializeObject<Bike>(jsonVehicle);
polymorphicVehicles.Add(aBike);
break;
default:
break;
}
}
// this is just to print it out!
var jsonPolymorphicVehicles = JsonConvert.SerializeObject(polymorphicVehicles);
Console.WriteLine("XML:");
Console.WriteLine(xml);
Console.WriteLine("");
Console.WriteLine("Polymorphic to jason");
Console.WriteLine(jsonPolymorphicVehicles);
Console.WriteLine("");
Console.WriteLine("Press key to exit!");
Console.Read();
}
}
public class Vehicle
{
public string Name = "Vehicle";
}
public class Car : Vehicle
{
public Car()
{
Name = "Car";
}
}
public class Bike : Vehicle
{
public Bike()
{
Name = "Bike";
}
}
public class Truck : Vehicle
{
public Truck()
{
Name = "Truck";
}
}
public class Vehicles
{
public List<Vehicle> Items { get; } = new List<Vehicle>();
}
public static class MyStaticClass
{
public static T XmlDeserializeFromString<T>(this string objectData)
{
return (T)XmlDeserializeFromString(objectData, typeof(T));
}
public static string XmlSerializeToString(this object objectInstance)
{
var serializer = new XmlSerializer(objectInstance.GetType());
var sb = new StringBuilder();
using (TextWriter writer = new StringWriter(sb))
{
serializer.Serialize(writer, objectInstance);
}
return sb.ToString();
}
public static object XmlDeserializeFromString(this string objectData, Type type)
{
var serializer = new XmlSerializer(type);
object result;
using (TextReader reader = new StringReader(objectData))
{
result = serializer.Deserialize(reader);
}
return result;
}
}
Expectation: Read the list of ints from the XML-file to the List called itemPool;
Result: "InvalidOperationException: Failed to add type System.Collections.Generic.List`1[System.Int32] to known type collection. There already is a registered type for XML name http://schemas.microsoft.com/2003/10/Serialization/Arrays:ArrayOfint"
I have to following code:
using System.Collections.Generic;
using System.Runtime.Serialization;
using Characters;
using Items;
[DataContract(Name ="Savefile", Namespace ="")]
public class Savefile
{
[DataMember(Name ="Characters")]
public List<Character> characters = new List<Character>();
[DataMember(Name = "ItemPool")]
public List<int> itemPool = new List<int>();
public void Initialize()
{
foreach (Character c in characters)
c.Initialize();
ItemPool.Load(itemPool.ToArray());
}
}
And another class with the following method:
public static void LoadFromSavefile()
{
DataContractSerializer serializer = new DataContractSerializer(typeof(Savefile));
FileStream stream = new FileStream(Path.Combine(Application.dataPath, _savefilePath), FileMode.Open);
_currentSave = serializer.ReadObject(stream) as Savefile;
stream.Close();
}
And the following xml-file that the class above reads from.
<?xml version="1.0" encoding="utf-8"?>
<Savefile xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Characters>
<Character>
<... not relevant clutter.../>
</Character>
</Characters>
<ItemPool>
<value>1</value>
</ItemPool>
</Savefile>
Edited using DataContractSerializer.
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Runtime.Serialization;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
namespace UnitTestProject1 {
[DataContract(Name = "Savefile", Namespace = "")]
public class Savefile {
[DataMember(Name = "Characters", Order = 0)]
public Characters Characters { get; private set; }
[DataMember(Name = "ItemPool", Order = 1)]
public Items ItemPool { get; private set; }
}
[CollectionDataContract(Name = "Characters", ItemName = "Character", Namespace = "")]
public class Characters : List<Character> {
}
public class Character {
public string Weapon { get; set; }
internal void Initialize() {
throw new NotImplementedException();
}
}
[CollectionDataContract(Name = "ItemPool", ItemName = "Item", Namespace = "")]
public class Items : List<int> {
public int value { get; set; }
}
[TestClass]
public class UnitTestSerialization {
[TestMethod]
public void TestMethod1() {
DataContractSerializer serializer = new DataContractSerializer(typeof(Savefile));
FileStream stream = new FileStream("SaveFile2.xml", FileMode.Open);
XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(stream, new XmlDictionaryReaderQuotas());
Savefile _currentSave = (Savefile)serializer.ReadObject(reader);
Assert.IsNotNull(_currentSave);
stream.Close();
}
}
}
xml file
<?xml version="1.0" encoding="utf-8"?>
<Savefile>
<Characters>
<Character>
<Weapon>Axe</Weapon>
</Character>
<Character>
<Weapon>Mace</Weapon>
</Character>
<Character>
</Character>
</Characters>
<ItemPool>
<Item>1</Item>
<Item>2</Item>
</ItemPool>
</Savefile>
I don't know if the topic is correct, if not please correct. So far i am not sure what to search for my problem so maybe the question has already been answered before.
Currently i have the following class (as example):
[Serializable]
public class Sample
{
public string Something { get; set; }
public List<Parameter> Parameters { get; set; }
}
[Serializable]
public class Parameter
{
public string Name { get; set; }
public string Value { get; set; }
}
This structure i have to serialize to the following XML:
<Sample>
<Something>1234512345112345</Something>
<Parameters>
<Name>Value</Name>
<Name>Value</Name>
</Parameters>
</Sample>
So the XML should contain the property value of the attribute "Name" as XML-Element Name.
Update 20.05.2015
I have the following XML content:
<?xml version="1.0" encoding="utf-16" ?>
<ProcessData>
<ID>123456</ID>
<IDYTPE>BASEPLATE</IDYTPE>
<State>FAIL</State>
<Recipe>654321</Recipe>
<ProcessDataParameter>
<test_0>0</test_0>
<test_1>12,34</test_1>
<test_2>24,68</test_2>
<test_3>37,02</test_3>
<test_4>49,36</test_4>
<test_5>61,7</test_5>
</ProcessDataParameter>
</ProcessData>
When i try to use the following code to deserialize:
public void ReadXml(XmlReader reader)
{
reader.ReadStartElement("ProcessData");
this.Id = reader.ReadElementString("ID");
this.IdType = reader.ReadElementString("IDYTPE");
this.State = reader.ReadElementString("State");
this.Recipe = reader.ReadElementString("Recipe");
reader.ReadStartElement("ProcessDataParameter");
this.ProcessDataParameter = new List<ProcessDataParameter>();
var subTree = reader.ReadSubtree();
while (subTree.Read())
{
if (subTree.NodeType == XmlNodeType.Text)
{
var nm = subTree.LocalName;
//Parameters.Add(new Parameter { Name = nm, Value = subTree.Value });
}
}
reader.ReadEndElement();
}
Everything gets read out fine expect the process data parameters.
It seems like the subTree.Read() just reades the element out of the XML content instead of all elements contained in the .
In the while loop the reader goes through the following values (debuged)
test_0 (start tag)
0 (value between the tag)
test_0 (end tag
and then out of the while.
Seems like the reader sees the as an subtree.
Further only the 0 - value gets recognized as XmlNodeType.Text
You could implement IXmlSerializable and create your own custom serialization behaviour for your Sample class. So in your case something like this should work
[Serializable]
public class Sample : IXmlSerializable
{
public string Something { get; set; }
public List<Parameter> Parameters { get; set; }
public XmlSchema GetSchema()
{
return null;
}
public void ReadXml(XmlReader reader)
{
XmlDocument doc = new XmlDocument();
doc.Load(reader);
Something = doc.SelectSingleNode(#"/Sample/Something").FirstChild.Value;
var parameters = doc.SelectSingleNode(#"/Sample/Parameters");
if (parameters.HasChildNodes)
{
Parameters = new List<Parameter>();
foreach (XmlElement childNode in parameters.ChildNodes)
{
Parameters.Add(new Parameter {Name = childNode.LocalName, Value = childNode.FirstChild.Value});
}
}
}
public void WriteXml(XmlWriter writer)
{
writer.WriteElementString("Something", this.Something);
writer.WriteStartElement("Parameters");
foreach (var parameter in Parameters)
{
writer.WriteElementString(parameter.Name, parameter.Value);
}
writer.WriteEndElement();
}
}
Updated to include ReadXml implementation for deserialization
I'm not quite sure if the ReadXml is complete as I can't test this now, you might have to tweak it a bit for the Parameters
Try this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
Sample sample = new Sample(){
Something = "1234512345112345",
Parameters = new List<Parameter>(){
new Parameter(){
Name = new List<string>(){"Value", "Value"}
}
}
};
XmlSerializer serializer = new XmlSerializer(typeof(Sample));
StreamWriter writer = new StreamWriter(FILENAME);
serializer.Serialize(writer, sample);
writer.Flush();
writer.Close();
writer.Dispose();
XmlSerializer xs = new XmlSerializer(typeof(Sample));
XmlTextReader reader = new XmlTextReader(FILENAME);
Sample newSample = (Sample)xs.Deserialize(reader);
}
}
[XmlRoot("Sample")]
public class Sample
{
[XmlElement("Something")]
public string Something { get; set; }
[XmlElement("Parameters")]
public List<Parameter> Parameters { get; set; }
}
[XmlRoot("Parameters")]
public class Parameter
{
[XmlElement("Name")]
public List<string> Name { get; set; }
}
}
I have a class need to be serialized.
namespace serializedobject
{
[DataContract]
public class Class1
{
string string1_;
string string2_;
EntityA entity_;
[DataMember]
public string string3
{
get { return string1_; }
set { string1_ = value; }
}
[DataMember]
public string string2
{
get { return string2_; }
set { string2_ = value; }
}
[DataMember]
public EntityA Entity
{
get { return entity_; }
set { entity_ = value; }
}
public static Class1 FromXML(string desc)
{
using (MemoryStream ms = new MemoryStream())
{
StreamWriter writer = new StreamWriter(ms);
writer.Write(desc);
writer.Flush();
ms.Seek(0, 0);
DataContractSerializer ser = new DataContractSerializer(typeof(Class1));
return (Class1)ser.ReadObject(ms);
}
}
public string ToXML()
{
using (MemoryStream ms = new MemoryStream())
{
DataContractSerializer ser = new DataContractSerializer(typeof(Class1));
ser.WriteObject(ms, this);
ms.Seek(0, 0);
StreamReader reader = new StreamReader(ms);
return reader.ReadToEnd();
}
}
}
[DataContract]
public class EntityA
{
string name_;
[DataMember]
public string Name
{
get { return name_; }
set { name_ = value; }
}
}
}
it is works fine with FromXML and ToXML. one of serialized context like:
<Class1 xmlns="http://schemas.datacontract.org/2004/07/serializedobject" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><Entity><Name>az</Name></Entity><string2 i:nil="true"/><string3>test</string3></Class1>
Later I need to move class EntityA to another namespace "outside", now the serialized context like:
<Class1 xmlns="http://schemas.datacontract.org/2004/07/serializedobject" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><Entity xmlns:a="http://schemas.datacontract.org/2004/07/outside"><a:Name>az</a:Name></Entity><string2 i:nil="true"/><string3>test</string3></Class1>
but now the serialized xml which created before change namespace can't be deserialized correctly. I guess this is because of for class "EntityA" changed namespace (xmlns:a added).
does anybody run into the problem before? any suggestion?
You can stop the namespace being added to the XML by specifying [DataContract(Namespace="")]. This relies on you setting that attribute BEFORE you save any xml code.
You can use this approach only if you have not already serialized any data, so this is the approach you would use when first designing a class to be serialized.
(If you have already got serialized data that you must deal with, see the second part of my answer below.)
This code sample has the two classes called Demo in two different namespaces, Test1 and Test2.
We serialize the code using the class from one namespace, and deserialize it using the class from the other namespace:
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Xml;
namespace ConsoleApp1
{
namespace Test1
{
[DataContract(Namespace="")]
public sealed class Demo
{
[DataMember]
public string Value { get; set; }
}
}
namespace Test2
{
[DataContract(Namespace="")]
public sealed class Demo
{
[DataMember]
public string Value { get; set; }
}
}
sealed class Program
{
private void run()
{
string filename = Path.GetTempFileName();
var demo1 = new Test1.Demo {Value = "DEMO"};
ToFile(filename, demo1);
var demo2 = FromFile<Test2.Demo>(filename);
Console.WriteLine(demo2.Value);
}
public static void ToFile(string filename, object obj)
{
DataContractSerializer serializer = new DataContractSerializer(obj.GetType());
using (var streamWriter = File.CreateText(filename))
using (var xmlWriter = XmlWriter.Create(streamWriter, new XmlWriterSettings{Indent = true}))
{
serializer.WriteObject(xmlWriter, obj);
}
}
public static T FromFile<T>(string filename)
{
DataContractSerializer serializer = new DataContractSerializer(typeof(T));
using (var textReader = File.OpenText(filename))
using (var xmlReader = XmlReader.Create(textReader))
{
return (T)serializer.ReadObject(xmlReader);
}
}
[STAThread]
static void Main(string[] args)
{
new Program().run();
}
}
}
If you have already serialized data without the Namespace="" attribute, then you will need instead to apply the appropriate namespace to the new class:
namespace Test1
{
[DataContract]
public sealed class Demo
{
[DataMember]
public string Value { get; set; }
}
}
namespace Test2
{
// Note the namespace includes both nested namespaces, i.e. ConsoleApp1.Test1
[DataContract(Namespace="http://schemas.datacontract.org/2004/07/ConsoleApp1.Test1")]
public sealed class Demo
{
[DataMember]
public string Value { get; set; }
}
}
is it possible to partially (de)/serialize an object from/into a string?
class Foo
{
Bar Bar{get;set;}
string XmlJunkAsString{get;set;}
}
so ultmately, we would want the string below to work...
<Foo><Bar></Bar><XmlJunkAsString><xml><that/><will/><not/><be/><parsed/></xml></XmlJunkAsString></Foo>
and ultimately we could find the contents of Foo.XmlJunkAsString to contain the string
<xml><that/><will/><not/><be/><parsed/></xml>
and vice-versa would occur where the xml above would be generated when this particular instance of Foo is serialized.
possible?
I was hoping that [XmlText] would work, but it seems to get escaped; you could implement IXmlSerializable, but that is very tricky. The following is ugly, but gives the right result (although you might get some xml whitespace differences)
using System;
using System.ComponentModel;
using System.Xml;
using System.Xml.Serialization;
public class Bar { }
public class Foo
{
public Bar Bar { get; set; }
[XmlIgnore]
public string XmlJunkAsString { get; set; }
[XmlElement("XmlJunkAsString"), Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
public XmlElement XmlJunkAsStringSerialized
{
get
{
string xml = XmlJunkAsString;
if (string.IsNullOrEmpty(xml)) return null;
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
return doc.DocumentElement;
}
set
{
XmlJunkAsString = value == null ? null : value.OuterXml;
}
}
}
static class Program {
static void Main()
{
var obj = new Foo
{
Bar = new Bar(),
XmlJunkAsString = "<xml><that/><will/><not/><be/><parsed/></xml>"
};
var ser = new XmlSerializer(obj.GetType());
ser.Serialize(Console.Out, obj);
}
}