Reputation: 763
I have a program which is deserializing an XML stream into an object, making some small changes, then serializing to XML. But the problem here is the resulting serialized XML is missing elements.
Here is a minimal program that shows what I am experiencing:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Diagnostics;
using System.IO;
using System.Xml.Serialization;
namespace Playground
{
class Program
{
static string str = @"<report>
<residential>
<dwelling />
<property />
<detachedStructures />
</residential>
</report>";
static void Main(string[] args)
{
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(str));
XmlSerializer s = new XmlSerializer(typeof(report));
report r = s.Deserialize(ms) as report;
MemoryStream ms2 = new MemoryStream();
s.Serialize(ms2, r);
ms2.Position = 0;
string output = new StreamReader(ms2).ReadToEnd();
System.Diagnostics.Debugger.Break();
}
}
[Serializable]
[XmlRoot("report")]
public class report
{
[XmlElement("residential")]
public XmlElement residential;
[XmlElement("residentialCaseHeader")]
public residentialCaseHeader residentialCaseHeader;
}
[System.SerializableAttribute()]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class residentialCaseHeader
{
}
}
note: After the deserialize step, the one really odd thing I noticed was that it said the element name of "r.residential" was "dwelling".
Here is the output from the program:
<?xml version="1.0"?>
<report xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<residential>
<dwelling />
</residential>
</report>
It appears like I am only getting the first child of my residential element... can anybody make sense of this and tell me what I am doing incorrectly?
Upvotes: 1
Views: 633
Reputation: 426
Consider using \[XmlAnyElement\]
Something like
[Serializable]
[XmlRoot("report")]
public class report
{
[XmlAnyElement("residential")]
public XmlElement[] residential;
[XmlElement("residentialCaseHeader")]
public residentialCaseHeader residentialCaseHeader;
}
Upvotes: 2
Reputation: 402
The report class should match up with all the XML elements. So there should be a another class for the element residential with the fields dwelling, property, detached structures.
So this is what I would do with it.
[Serializable]
public class Residential
{
public string dwelling;
public string property;
public string detachedStructures;
}
[Serializable]
public class report
{
public Residential residential;
}
Upvotes: 0