将XML反序列化为具有xmlns名称空间问题的对象

时间:2018-09-18 13:58:05

标签: c# soap xml-deserialization

您好,我不断收到错误消息:

 Sub clean_data()


Dim Preliminary_MTM As Worksheet
Dim Sheetlink As String

Sheetlink = Worksheets("Input for model").Range("E17").Value

Set Preliminary_MTM = Sheets(Sheetlink)

Preliminary_MTM.Activate

尝试了一些我在互联网上发现的东西,但都失败了。

这是我调用SOAP Api时输出的XML:

<ArrayOfThemes xmlnx='http://brickset.com/api/'> was not expected.

课程:

    <ArrayOfThemes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="https://brickset.com/api/">
      <themes>
        <theme>4 Juniors</theme>
        <setCount>24</setCount>
        <subthemeCount>5</subthemeCount>
        <yearFrom>2003</yearFrom>
        <yearTo>2004</yearTo>
      </themes>
   </ArrayOfThemes>

然后通常是通常的反序列化代码。仍然无法将XML对象转换为主题列表。

您如何处理xmlns命名空间?

1 个答案:

答案 0 :(得分:1)

在反序列化结果之前,可以使用XmlTextReader忽略名称空间。 同样,除非您只希望有一个,否则ArrayOfThemes类可能应该有一个主题数组。下面的示例用于反序列化该xml。

class Program
{
    static void Main(string[] args)
    {
        var xml = @"<ArrayOfThemes xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns=""https://brickset.com/api/"">
            <themes>
            <theme>4 Juniors</theme>
            <setCount>24</setCount>
            <subthemeCount>5</subthemeCount>
            <yearFrom>2003</yearFrom>
            <yearTo>2004</yearTo>
            </themes>
            </ArrayOfThemes>";
        var ms = new MemoryStream(Encoding.UTF8.GetBytes(xml));
        var reader = new XmlTextReader(ms) {Namespaces = false};
        var serializer = new XmlSerializer(typeof(ArrayOfThemes));

        var result = (ArrayOfThemes) serializer.Deserialize(reader);
    }
}

public class Themes
{
    [XmlElement("theme")]
    public string Theme { get; set; }
    [XmlElement("setCount")]
    public string SetCount { get; set; }
    [XmlElement("subthemeCount")]

    public string SubthemeCount { get; set; }
    [XmlElement("yearFrom")]

    public string YearFrom { get; set; }
    [XmlElement("yearTo")]

    public string YearTo { get; set; }
}

[Serializable, XmlRoot("ArrayOfThemes")]
public class ArrayOfThemes
{
    [XmlElement("themes")]
    public Themes[] Themes { get; set; }
}