将字符串(xml节点,如语法)反序列化为c#对象

时间:2016-12-30 20:42:01

标签: c# xml xml-deserialization

我正在尝试将字符串反序列化为对象。 xml节点是否像语法一样,但不是xml(因为没有根节点或命名空间)。这是我到目前为止,有这个错误:

  

<delivery xmlns=''>. was not expected

反序列化代码:

var number = 2;
var amount = 3;
var xmlCommand = $"<delivery number=\"{number}\" amount=\"{amount}\" />";
XmlSerializer serializer = new XmlSerializer(typeof(Delivery));
var rdr = new StringReader(xmlCommand);
Delivery delivery = (Delivery)serializer.Deserialize(rdr);

交付对象:

using System.Xml.Serialization;

namespace SOMWClient.Events
{
    public class Delivery
    {
        [XmlAttribute(AttributeName = "number")]
        public int Number { get; set; }

        [XmlAttribute(AttributeName = "amount")]
        public string Amount { get; set; }

        public Delivery()
        {

        }
    }
}

如何在反序列化时避免xmlns错误?

2 个答案:

答案 0 :(得分:0)

像这样自己添加root:

XmlRootAttribute root = new XmlRootAttribute();
root.ElementName = "delivery";
// root.Namespace = "http://www.whatever.com";
root.IsNullable = true;

// your code goes below

答案 1 :(得分:0)

更改Delivery类并添加有关根元素的信息(XmlRoot属性):

[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[XmlRoot("delivery")]
public class Delivery
{
    [XmlAttribute(AttributeName = "number")]
    public int Number { get; set; }

    [XmlAttribute(AttributeName = "amount")]
    public string Amount { get; set; }

    public Delivery()
    { }
}