【问题标题】:deserialize a string (xml node like syntax) to c# object将字符串(类似xml节点的语法)反序列化为c#对象
【发布时间】:2016-12-30 20:42:00
【问题描述】:

我正在尝试将字符串反序列化为对象。是类似于语法的 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错误?

【问题讨论】:

    标签: c# xml xml-deserialization


    【解决方案1】:

    更改 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()
        { }
    } 
    

    【讨论】:

      【解决方案2】:

      像这样自己添加根:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-29
        • 1970-01-01
        • 2021-04-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多