【问题标题】:How to add attributes for C# XML Serialization如何为 C# XML 序列化添加属性
【发布时间】:2010-11-03 23:37:24
【问题描述】:

我在序列化和对象方面遇到问题,我可以让它创建所有正确的输出,除了我有一个需要值和属性的元素。这是所需的输出:

<Root>
  <Method>Retrieve</Method>
  <Options>
    <Filter>
      <Times>
        <TimeFrom>2009-06-17</TimeFrom>
      </Times>
      <Document type="word">document name</Document>
    </Filter>
  </Options>
</AdCourierAPI>

我可以全部构建但找不到设置文档类型属性的方法,这是对象类的一部分

[XmlRoot("Root"), Serializable]    
public class Root    
{    
    [XmlElement("Method")]    
    public string method="RetrieveApplications";    
    [XmlElement("Options")]    
    public _Options Options;    
}    
public class _Options    
{
    [XmlElement("Filter")]    
    public _Filter Filter;    
}
public class _Filter    
{
    [XmlElement("Times")]    
    public _Times Times;    
    [XmlElement("Documents")]    
    public string Documents;    
}

这给了我:

<Document>document name</Document>

而不是:

<Document type="word">document name</Document>

但我找不到解决此问题的方法,请指教。

谢谢

【问题讨论】:

  • 对不起,马克……你一定是在我之前收到了那个编辑。
  • Mark Gravell 拯救了我的一天! :-) 谢谢!

标签: c# xml-serialization


【解决方案1】:

type 存储在哪里?

通常你可以有类似的东西:

class Document {
    [XmlAttribute("type")]
    public string Type { get; set; }
    [XmlText]
    public string Name { get; set; }
}


public class _Filter    
{
    [XmlElement("Times")]    
    public _Times Times;    
    [XmlElement("Document")]    
    public Document Document;    
}

【讨论】:

  • 谢谢各位,已排序,非常感谢
  • 哇,这太棒了,本来以为会更复杂。
【解决方案2】:

string 类没有type 属性,因此您不能使用它来创建所需的输出。您应该创建一个 Document 类:

public class Document
{
    [XmlText]
    public string Name;

    [XmlAttribute("type")]
    public string Type;
}

您应该将Document 属性更改为输入Document

【讨论】:

  • 我同意(正要提交同样的事情!)
【解决方案3】:

听起来你需要一个额外的课程:

public class Document
{
    [XmlAttribute("type")]
    public string Type { get; set; }
    [XmlText]
    public string Name { get; set; }
}

实例(在示例中)将具有Type = "word"Name = "document name"documents 将是 List&lt;Document&gt;

顺便说一句 - 公共领域很少是个好主意...

【讨论】:

    【解决方案4】:

    您可以使用 XmlWriter 而不是 XmlSerialization 来获得此效果。 它更复杂,但如果模型中有很多字符串,它将是更清洁的解决方案。

    创建自己的CustomeAttribute,例如:

    [System.AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
    public class MyCustomAttribute : System.Attribute
    {
        public MyCustomAttribute (string type)
        {
            MyType = type;
        }
        public string MyType { get; set; }
    }
    

    然后在模型中添加它,像这样:

    public class MyModel
    {
        [MyCustom("word")]
        public string Document { get; set; }
        [MyCustom("time")]
        public string Time { get; set; }
    }
    

    最后一部分是使用此参数创建 xml。 你可以这样做:

            var doc = new XmlDocument();
            MyModel myModel = new MyModel();//or get it from somewhere else
            using (Stream s = new MemoryStream())
            {
                var settings = new XmlWriterSettings();
                settings.Async = true;
                settings.Indent = true;
                var writer = XmlTextWriter.Create(s, settings);
                await writer.WriteStartDocumentAsync();
                await writer.WriteStartElementAsync(null,"Root", null);
    
                myModel.GetType().GetProperties().ToList().ForEach(async p =>
                {
                    dynamic value = p.GetValue(myModel);
                    writer.WriteStartElement(p.Name);
                    var myCustomAttribute = p.GetCustomAttributes(typeof(MyCustomAttribute), false).FirstOrDefault() as MyCustomAttribute;
                    if(myCustomAttribute != null)
                    {
                        await writer.WriteAttributeStringAsync(null, "MyType", null, myCustomAttribute.MyType );
                    }
    
                    writer.WriteValue(value);
                    await writer.WriteEndElementAsync();
                });
    
                await writer.WriteEndElementAsync();
                await writer.FlushAsync();
                s.Position = 0;
                doc.Load(s);                
                writer.Close();
            }
            string myXml = doc.OuterXml
    

    在 myXml 中应该是这样的: (数值为示例)

    <?xml version="1.0" encoding="utf-8"?>
    <Root>
        <Document MyType="word">something</Document>
        <Time MyType="time">11:31:29</Time>
    </Root>
    

    当然,你可以用其他方式来做。 在这里,您有一些对我有帮助的文档: https://docs.microsoft.com/en-us/dotnet/api/system.xml.xmlwriter?view=netframework-4.8#writing_elements

    【讨论】:

      猜你喜欢
      • 2013-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多