[英]Passing an Xml from a Web Service
I have a web service which returns something of type MyData
.我有一个 web 服务,它返回
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.我已将
Object[]
用于DataItems
,因为数组的类型可能有多种类型。 I have two different classes which I could successfully send using this method.我有两个不同的类,我可以使用这种方法成功发送它们。 See below.
见下文。
clientResults
is the filled DataSet. clientResults
是填充的数据集。
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!我可以轻松地将
MyFirstClass
更改为MySecondClass
并设置其自己的属性,web 服务将正确序列化这两个类,每个人都很高兴!
However now there is a need where I have to pass an XML returned by the DataSet.GetXml()
function.但是现在需要传递由
DataSet.GetXml()
function 返回的 XML。
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.所以我想,好吧,让我们用 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?如何通过 web 服务正确传递 XML?
The answer was pretty easy.答案很简单。 All I had to do was create a parent class which other classes were going to inherit from.
我所要做的就是创建一个父 class 其他类将从中继承。
public class BaseData
{
}
public class XmlData : BaseData
{
public XmlNode xml;
}
And I made the Object[]
to a BaseData[]
.我将
Object[]
设为BaseData[]
。
public class MyData
{
public string Name;
[XmlElement("item")]
public BaseData[] DataItems;
}
And then I selected the node using XPath and assigned it.然后我使用 XPath 选择节点并分配它。
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.我还必须将
XmlInclude(typeof(XmlData))
放入 web 服务方法签名。
And it was working perfectly!它运行良好!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.