I have a web service which returns something of type MyData.
public class MyData
{
public string Name;
[XmlElement("item")]
public Object[] DataItems;
}
I have used Object[] for DataItems because the type of array could be of several types. I have two different classes which I could successfully send using this method. See below.
clientResults is the filled DataSet.
MyData returnResult = new MyData();
MyFirstClass[] resultData = new MyFirstClass[clientResults.Tables[0].Rows.Count];
resultData.MyFirstClassProperty1 = "Blah Blah";
resultData.MyFirstClassProperty2 = "Blah Blah";
returnResult.DataItems = resultData.
I could easily change MyFirstClass to MySecondClass and set its own properties and the web service would properly serialize both the classes and every one was happy!
However now there is a need where I have to pass an XML returned by the DataSet.GetXml() function.
Naturally, what I did was
XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(clientResults.GetXml());
resultData.DataItems = new XmlDocument[] { xdoc };
But this is throwing an exception
System.InvalidOperationException: There was an error generating the XML document. ---> System.InvalidOperationException: The type System.Xml.XmlDocument may not be used in this context.
So what I thought, ok lets try it with XmlNode.
XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(clientResults.GetXml());
XmlNode xElement = xdoc.SelectSingleNode("/");
result.DataItems = new XmlNode[] { xElement };
Still its throwing the SAME exception. What could be wrong?
How do I properly pass an XML through a web service?
The answer was pretty easy. All I had to do was create a parent class which other classes were going to inherit from.
And I made the
Object[]to aBaseData[].And then I selected the node using XPath and assigned it.
I also had to put a
XmlInclude(typeof(XmlData))to the web service method signature.And it was working perfectly!