【问题标题】:XML serialization node name with key value带有键值的 XML 序列化节点名称
【发布时间】:2016-08-24 03:43:02
【问题描述】:

我想将我的代码序列化为 XML。

现在我有:

<?xml version="1.0" encoding="utf-8"?>
<SerializationClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Value>Test</Value>
</SerializationClass>

我的 C# 代码如下所示:

public class SerializationClass
{
[XmlElement("Value")]
public string City { get; set; }
}

但我希望有这样的 XML:

<?xml version="1.0" encoding="utf-8"?>
<SerializationClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <City value="Test"></City>
</SerializationClass>

【问题讨论】:

  • 1) stackoverflow.com/help/how-to-ask 2) 你要的xml无效。 (见 MyCityName 标签) 3) 表现出一些努力,你尝试过什么?
  • 那么是否有可能获得如下 XML: /

标签: c# xml wcf serialization xml-serialization


【解决方案1】:

你不能用你拥有的类结构来做到这一点(没有手工编码)。如果您愿意更改结构,这将起作用:

public class SerializationClass
{
    public City City { get; set; }
}

public class City
{
    [XmlAttribute("value")]
    public string Value { get; set; }
}

【讨论】:

    【解决方案2】:

    这种方法怎么样?

    public class SerializationClass
    {
        [XmlIgnore]
        public string City { get; set; }
    
        [EditorBrowsable(EditorBrowsableState.Never)]
        [XmlAnyElement]
        public XElement _City
        {
            get { return new XElement("City", new XAttribute("value", City)); }
            set { City = value.FirstAttribute.Value; }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-25
      • 2015-10-31
      • 1970-01-01
      相关资源
      最近更新 更多