当嵌套对象具有namesapce时,如何反序列化XML

时间:2016-07-02 13:49:49

标签: c# xml deserialization xml-namespaces xml-deserialization

给出以下XML:

"x"

以下c#:

<webParts>
  <webPart xmlns="http://schemas.microsoft.com/WebPart/v3">
    <title>Title One</title>
  </webPart>
  <webPart xmlns="http://schemas.microsoft.com/WebPart/v3">
    <title>Title Two</title>
  </webPart>
</webParts>

我试图反序列化XML。我无法控制XML,我可以更改c#。如果我删除webPart元素中的命名空间,可以在反序列化期间执行此操作,它可以正常工作。然而,似乎有点kludgy。我觉得应该在类中添加XML属性,但却无法找到Namespace标记的正确组合。上面的代码反序列化webParts,但计数为0,没有webPart元素被反序列化。为了使这项工作,应该对c#做些什么?谢谢!

1 个答案:

答案 0 :(得分:2)

在大多数情况下,使用VS。

从XML构建类是一项非常容易的任务

您问题中的XML将转换为该结构

/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute( "code" )]
[System.Xml.Serialization.XmlTypeAttribute( AnonymousType = true )]
[System.Xml.Serialization.XmlRootAttribute( Namespace = "", IsNullable = false )]
public partial class webParts
{

    private webPart[ ] webPartField;        

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute( "webPart", Namespace = "http://schemas.microsoft.com/WebPart/v3" )]
    public webPart[ ] webPart
    {
        get 
        {
            return this.webPartField;
        }
        set
        {
            this.webPartField = value;
        }
    }
}

/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute( "code" )]
[System.Xml.Serialization.XmlTypeAttribute( AnonymousType = true, Namespace = "http://schemas.microsoft.com/WebPart/v3" )]
[System.Xml.Serialization.XmlRootAttribute( Namespace = "http://schemas.microsoft.com/WebPart/v3", IsNullable = false )]
public partial class webPart
{

    private string titleField;

    /// <remarks/>
    public string title
    {
        get
        {
            return this.titleField;
        }
        set
        {
            this.titleField = value;
        }
    }
}

可用于转换xml

public partial class webParts
{
    static public webParts FromXml(string path)
    {
        webParts returnValue = null;
        var serializer = new XmlSerializer(typeof(webParts));
        using (var stream = File.OpenRead(path))
        {
            returnValue = (webParts)serializer.Deserialize(stream);
        }
        return returnValue;
    }
}