C# 如何使用 DataContract 添加 XML 属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1644004/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I add an XML attribute using DataContract
提问by Magpie
I have a simple class I'm serializing.
我有一个正在序列化的简单类。
[DataContract(Name = "Test", Namespace = "")]
public class Test
{
[DataMember(Order = 0, Name = "Text")]
public string Text { get; set; }
public Test() {}
}
This kicks out the following XML:
这将踢出以下 XML:
<Test>
<Text>Text here</Text>
</Test>
What I want is:
我想要的是:
<Test>
<Text type="MyType">Text here</Text>
</Test>
How do I add attributes the the XML elements?
如何为 XML 元素添加属性?
Thanks in advance.
提前致谢。
采纳答案by Pete OHanlon
You can't add attributes to a DataContract. You either have to use a class that Implements ISerializable or use the .Net XmlSerializer.
您不能向 DataContract 添加属性。您要么必须使用实现 ISerializable 的类,要么使用 .Net XmlSerializer。
回答by Nikolay R
Not exactly an answer, but you can try to implement IXmlSerializable to fully control output xml format.
不完全是答案,但您可以尝试实现 IXmlSerializable 以完全控制输出 xml 格式。
回答by guiomie
I was able to achieve this by declaring an XElement which has attributes defined in it. Ex:
我能够通过声明一个其中定义了属性的 XElement 来实现这一点。前任:
public XElement Text { get; set;}
回答by Remcoenator
Add the type attribute with [XMLAttribute] and the element value with [XmlText].
添加带有 [XMLAttribute] 的类型属性和带有 [XmlText] 的元素值。
public class Test
{
public text Text;
public Test()
{
Text = new text();
}
[DataContract(Name = "Test", Namespace = "")]
public class text
{
[XmlText]
public string Text { get; set; }
[XmlAttribute]
public string type { get; set; }
}
}