【问题标题】:.net / wcf: deserialization of an xml with xsi:type.net / wcf:使用 xsi:type 反序列化 xml
【发布时间】:2014-10-08 14:00:08
【问题描述】:

我有一个小型 wcf 服务器,它接收带有 XML 的 POST 请求(请注意,我无法控制 XML)。我可以毫无问题地反序列化它,除非它具有 xsi:type = "something" 属性。

当我尝试序列化我的类时,一切正常(甚至 xsi:type 属性)。

XML:

<?xml version="1.0" encoding="utf-8"?>
<Node1 Att1="" Att2=""
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:type="SOMETHING" 
    xmlns="http://www.CIP4.org/JDFSchema_1_1"  
    xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Node2/>
</Node1>

当我发送此 XML 时,服务器会抛出错误请求 (400),但如果我删除“xsi:type="SOMETHING"”,一切正常。

这是我请求序列化类时服务器发送的内容:

<?xml version="1.0" encoding="utf-8"?>
<Node1 Att1="" Att2="" xsi:type="SOMETHING"
    xmlns="http://www.CIP4.org/JDFSchema_1_1" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Node2/>
</Node1>

如果序列化运行良好,为什么反序列化不行?

这是我的课:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.Xml.Serialization;
using System.Xml.Schema;

namespace ConsoleApplicationTest.dom
{

[Serializable()]
[XmlRoot(ElementName = "Node1", Namespace = "http://www.CIP4.org/JDFSchema_1_1")]
public class Test
{
    //attributes
    [XmlAttribute("Att1")]
    public string Att1 = "";
    [XmlAttribute("Att2")]
    public string Att2 = "";

    [XmlAttribute("type", Namespace = "http://www.w3.org/2001/XMLSchema-instance")]
    public string Type="typetypetype";



    [XmlElement("Node2")]
    public string node2 = "";


}




}

请帮帮我:(

【问题讨论】:

  • 我认为原因是'w3.org/2001/XMLSchema-instance:type'属性在反序列化时具有特殊含义。它应该告诉序列化器它应该创建一个映射到这个特定类型的对象。这是您的预期行为吗?
  • 我试图映射到某个类,但没有帮助。事实是我根本不需要这些信息,但它总是在我收到的 xml 中:/
  • 用 [XmlIgnore] 标记这个 Type 属性会有帮助吗?
  • 不,[XmlInore] 没有帮助

标签: c# xml wcf serialization


【解决方案1】:

试试这个课程:

[Serializable()]
[XmlRoot(ElementName = "Node1", Namespace = "http://www.CIP4.org/JDFSchema_1_1")]
public class SOMETHING
{
    //attributes
    [XmlAttribute("Att1")]
    public string Att1 = "";
    [XmlAttribute("Att2")]
    public string Att2 = "";

    [XmlElement("Node2")]
    public string node2 = "";


}

我的代码运行良好

   XmlSerializer ser = new XmlSerializer(typeof(SOMETHING));

    SOMETHING t = (SOMETHING)ser.Deserialize(new System.IO.StringReader(textBox1.Text));

【讨论】:

  • 感谢您的帮助,但是服务器只能接收 xml/json,我无法从流或字符串中反序列化。我只需要使用我的类来反序列化:/
猜你喜欢
  • 2015-10-24
  • 1970-01-01
  • 2015-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多