[英]WCF, XML deserialization
I have a simple WCF service 我有一个简单的WCF服务
[ServiceContract]
public interface IService1
{
[OperationContract]
string GetData(ShoppingCart value);
}
public class ShoppingCart
{
public string name;
[XmlElement("ShoppingCartItem")]
public ShoppingCartItem[] ShoppingCartItems;
}
public class ShoppingCartItem
{
public string Description;
}
And a simple test console. 和一个简单的测试控制台。 When I add my service reference to test console, My ShoppingCart class comes to TestConsole reference.cs file.
当我将服务引用添加到测试控制台时,My ShoppingCart类将出现在TestConsole reference.cs文件中。 So I can write like this on TestConsole project:
所以我可以在TestConsole项目上这样写:
static void Main(string[] args)
{
ShoppingCart body = new ShoppingCart();
FileStream myFileStream = new FileStream(@"C:\Resources\Xmls\New Folder\shoppingCart.xml", FileMode.Open);
XmlSerializer mySerializer = new XmlSerializer(typeof(ShoppingCart));
ShoppingCart cart = (ShoppingCart)mySerializer.Deserialize(myFileStream);
}
My shoppingCart.xml file is like this: 我的shoppingCart.xml文件是这样的:
<?xml version="1.0"?>
<ShoppingCart>
<name>test</name>
<ShoppingCartItem>
<Description>XBox 360</Description>
</ShoppingCartItem>
<ShoppingCartItem>
<Description>Cell Phone</Description>
</ShoppingCartItem>
</ShoppingCart>
So, I am waiting that when code comes to 所以,我等着代码来
ShoppingCart cart = (ShoppingCart)mySerializer.Deserialize(myFileStream);
line, there should be two items. 行,应该有两个项目。 But it seems like this:
但似乎是这样的:
Could you please explain why my list is not populated? 您能否解释为什么我的列表没有填写?
You need to add XmlElement attribute like this: 您需要像这样添加XmlElement属性:
public class ShoppingCart
{
[XmlElement("ShoppingCartItem")]
public ShoppingCartItem[] ShoppingCartItems;
}
If it's possible to change the Xml-file to this structure and remove the XmlElement attribute that's an alternative 如果可以将Xml文件更改为此结构并删除XmlElement属性,则可以选择
<ShoppingCart>
<name>test</name>
<ShoppingCartItems>
<ShoppingCartItem>
<Description>XBox 360</Description>
</ShoppingCartItem>
<ShoppingCartItem>
<Description>Cell Phone</Description>
</ShoppingCartItem>
</ShoppingCartItems>
</ShoppingCart>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.