XML反序列化愚蠢的问题

时间:2018-11-29 09:57:50

标签: c# xml

我正在寻找一种使用C#的方法,可以在下面将XML反序列化为一个类。我可以使用XmlDocument.LoadXml()读取它,但是我想将其反序列化为对象。

我试图对对象使用XmlSerializer:

[XmlRoot(ElementName = "properties", Namespace = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata") ]
public class MyDto
{
    [XmlElement(ElementName = "ObjectID", Namespace = "http://schemas.microsoft.com/ado/2007/08/dataservices")]
    public string ObjectID { get; set; }
    public string ContactID { get; set; }
}

我的代码(内存流中填充了xml):

var ms = new MemoryStream();
var w = XmlWriter.Create(ms, new XmlWriterSettings
{
    Indent = true,
    IndentChars = " ",
    OmitXmlDeclaration = false,
    Encoding = new UTF8Encoding(false),
});

XmlSerializer serializer = new XmlSerializer(typeof(MyDto));
var data = (MyDto)serializer.Deserialize(ms);

但是我得到了错误 System.InvalidOperationException:XML文档(0,0)中存在错误。 ---> System.Xml.XmlException:根元素丢失。

<?xml version="1.0" encoding="utf-8"?>
<Content type="application/xml">
 <m:properties xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">
  <d:ObjectID xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices">920D2</d:ObjectID>
  <d:ContactID xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices">99999</d:ContactID>
 </m:properties>
</Content>

1 个答案:

答案 0 :(得分:1)

您的XmlSerializer类对象完全错误或不适合您的XML。

您可以从xmltocsharp

获取xml的正确类对象。

尝试下面的类对象。

[XmlRoot("ObjectID", Namespace = "http://schemas.microsoft.com/ado/2007/08/dataservices")]
public class ObjectID
{
    [XmlAttribute("d", Namespace = "http://www.w3.org/2000/xmlns/")]
    public string D { get; set; }
    [XmlText]
    public string Text { get; set; }
}

[XmlRoot("ContactID", Namespace = "http://schemas.microsoft.com/ado/2007/08/dataservices")]
public class ContactID
{
    [XmlAttribute("d", Namespace = "http://www.w3.org/2000/xmlns/")]
    public string D { get; set; }
    [XmlText]
    public string Text { get; set; }
}

[XmlRoot("properties", Namespace = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata")]
public class Properties
{
    [XmlElement("ObjectID", Namespace = "http://schemas.microsoft.com/ado/2007/08/dataservices")]
    public ObjectID ObjectID { get; set; }
    [XmlElement("ContactID", Namespace = "http://schemas.microsoft.com/ado/2007/08/dataservices")]
    public ContactID ContactID { get; set; }
    [XmlAttribute("m", Namespace = "http://www.w3.org/2000/xmlns/")]
    public string M { get; set; }
}

[XmlRoot("Content")]
public class MyDto
{
    [XmlElement("properties", Namespace = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata")]
    public Properties Properties { get; set; }
    [XmlAttribute("type")]
    public string Type { get; set; }
}

输出:

enter image description here