如何添加C#xml序列化的属性

发布于 2025-01-28 12:01:52 字数 1160 浏览 4 评论 0原文

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

<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>

但是我找不到方法来纠正此问题, 请指教。

谢谢

I am having an issue with serializing and object, I can get it to create all the correct outputs except for where i have an Element that needs a value and an attribute. Here is the required output:

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

I can build all of it but can not find a way to set the Document type attribute, here is a segment of the object class

[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;    
}

which gives me:

<Document>document name</Document>

rather than:

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

but I can not find a way to correct this, please advise.

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

墨落成白 2025-02-04 12:01:52

您在哪里存储了类型

通常您可能会有类似的东西:

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;    
}

Where do you have the type stored?

Normally you could have something like:

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;    
}
记忆之渊 2025-02-04 12:01:52

字符串类没有类型属性,因此您无法使用它来创建所需的输出。您应该创建一个文档类:

public class Document
{
    [XmlText]
    public string Name;

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

您应该将文档属性更改为type document

The string class doesn't have a type property, so you can't use it to create the desired output. You should create a Document class instead :

public class Document
{
    [XmlText]
    public string Name;

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

And you should change the Document property to type Document

桃酥萝莉 2025-02-04 12:01:52

听起来您需要一个额外的类:

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

其中一个实例(在示例中)将具有type =“ Word”name =“ document name”; 文档将是list&lt; document&gt;

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

It sounds like you need an extra class:

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

Where an instance (in the example) would have Type = "word" and Name = "document name"; documents would be a List<Document>.

By the way - public fields are rarely a good idea...

胡渣熟男 2025-02-04 12:01:52

您可以使用XMLWriter而代替XMLSerialization来获得此效果。
它更为复杂,但是如果您在模型中有很多字符串,则将是更干净的解决方案。

例如,创建您自己的自定义图表:

[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://学习。 microsoft.com/en-us/dotnet/api/system.xml.xmlwriter?view=netframework-4.8#writing_elements

You can use XmlWriter instead XmlSerialization to get this effect.
It is more complex but if you have a lot of strings in model it will be cleaner solution.

Create your own CustomeAttribute, for example:

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

Then in model add it, like that:

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

The last part is to create xml with this arguments.
You can do it likes that:

        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

In myXml should be something like that:
(values are examples)

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

You can do it in other way, of course.
Here you have some docs which helped me:
https://learn.microsoft.com/en-us/dotnet/api/system.xml.xmlwriter?view=netframework-4.8#writing_elements

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文