【问题标题】:WCF, XML deserializationWCF、XML反序列化
【发布时间】:2015-03-29 23:35:24
【问题描述】:

我有一个简单的 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;
}

还有一个简单的测试控制台。当我将服务引用添加到测试控制台时,我的 ShoppingCart 类将出现在 TestConsole reference.cs 文件中。所以我可以在 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);    
}

我的 shoppingCart.xml 文件是这样的:

<?xml version="1.0"?>
 <ShoppingCart> 
   <name>test</name>
   <ShoppingCartItem>
     <Description>XBox 360</Description>
   </ShoppingCartItem>
   <ShoppingCartItem>
     <Description>Cell Phone</Description>
   </ShoppingCartItem>
</ShoppingCart> 

所以,我正在等待代码到来时

ShoppingCart cart = (ShoppingCart)mySerializer.Deserialize(myFileStream);

行,应该有两个项目。但看起来是这样的:

您能否解释一下为什么我的列表没有填写?

【问题讨论】:

    标签: c# xml wcf serialization deserialization


    【解决方案1】:

    您需要像这样添加 XmlElement 属性:

    public class ShoppingCart
    {
        [XmlElement("ShoppingCartItem")]
        public ShoppingCartItem[] ShoppingCartItems;
    }
    

    如果可以将 Xml 文件更改为此结构并删除作为替代的 XmlElement 属性

    <ShoppingCart>
      <name>test</name>
      <ShoppingCartItems>
       <ShoppingCartItem>
         <Description>XBox 360</Description>
       </ShoppingCartItem>
       <ShoppingCartItem>
         <Description>Cell Phone</Description>
       </ShoppingCartItem>
      </ShoppingCartItems>
    </ShoppingCart>
    

    【讨论】:

    • 你确定吗?我确实运行了它!
    • Daniel,如果我在一个简单的控制台项目中运行它,它就可以工作。但在我的情况下,我的真实对象(购物车)在 WCF 项目中,当我将服务引用添加到我的测试项目时,它会转到 testconsole。这一次它不起作用。你能试试这个case吗。谢谢你的帮助
    • 我不知道什么不起作用,您的 WCF 服务是如何实现的,您如何调用 WCF 服务?
    猜你喜欢
    • 1970-01-01
    • 2012-06-23
    • 1970-01-01
    • 1970-01-01
    • 2021-06-07
    • 2019-12-10
    • 1970-01-01
    • 2012-03-10
    • 2014-08-31
    相关资源
    最近更新 更多