I have this XML:
<ResultData xmlns="http://schemas.datacontract.org/2004/07/TsmApi.Logic.BusinesEntities"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Information>Schedule added.</Information>
<Success>true</Success>
</ResultData>
Is there a way to get as result only that:
<ResultData>
<Information>Sched added.</Information>
<Success>true</Success>
</ResultData>
Without all the other things from the example below? Because when I try to get the object of the result string shown below, it doesn't work.
Datacontract XML serialization
The code I try to use is:
var serializer = new XmlSerializer(typeof(ResultData));
var rdr = new StringReader(xmlResultString);
var resultingMessage = (ResultData)serializer.Deserialize(rdr);
And on the last row it shows me error:
An unhandled exception of type 'System.InvalidOperationException' occurred in System.Xml.dll
Additional information: There is an error in XML document (1, 2).
<ResultData xmlns='http://schemas.datacontract.org/2004/07/TsmApi.Logic.BusinesEntities'> was not expected.
ResultData:
[DataContract]
public class ResultData
{
[DataMember]
public bool Success
{
get;
set;
}
[DataMember]
public string Information
{
get;
set;
}
}
You are seeing the exception due to DataContract serialization namespace in the xml. Ideally you want to deserialize this with DataContractSerializer.
If you want to use XmlSerializer, then you will have to clean up the namespace declaration. Following will cleanup all the namespace and allow you to use XmlSerializer. In the foreach loop, we have to remove IsNamespaceDeclaration attribute and then set the element Name property to LocalName.
string xmlResultString = @"<ResultData xmlns=""http://schemas.datacontract.org/2004/07/TsmApi.Logic.BusinesEntities""
xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"">
<Information>Schedule added.</Information>
<Success>true</Success>
</ResultData>";
var doc = XDocument.Parse(xmlResultString);
foreach (var element in doc.Descendants())
{
element.Attributes().Where(a => a.IsNamespaceDeclaration).Remove();
element.Name = element.Name.LocalName;
}
xmlResultString = doc.ToString();
var rdr = new StringReader(xmlResultString);
var serializer = new XmlSerializer(typeof(ResultData));
var resultingMessage = (ResultData)serializer.Deserialize(rdr);