I have a simple WCF service
[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. So I can write like this on TestConsole project:
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:
<?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:
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
<ShoppingCart>
<name>test</name>
<ShoppingCartItems>
<ShoppingCartItem>
<Description>XBox 360</Description>
</ShoppingCartItem>
<ShoppingCartItem>
<Description>Cell Phone</Description>
</ShoppingCartItem>
</ShoppingCartItems>
</ShoppingCart>
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.