简体   繁体   中英

Passing an Xml from a Web Service

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.

public class BaseData
{

}

public class XmlData : BaseData
{
   public XmlNode xml;
}

And I made the Object[] to a BaseData[] .

public class MyData
 {
        public string Name;
        [XmlElement("item")]
        public BaseData[] DataItems;
 }

And then I selected the node using XPath and assigned it.

XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(clientResults.GetXml());
XmlNode xElement = xdoc.SelectSingleNode("/");

XmlData[] xmlData = new XmlData[1];
xmlData[0] = new XmlData();
xmlData[0].xml = xElement;

result.DataItems = xmlData;

I also had to put a XmlInclude(typeof(XmlData)) to the web service method signature.

And it was working perfectly!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM