C# XML 序列化问题 - 如何从一个对象序列化元素、属性和文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/797055/
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
XML Serialization question - How to Serialize Element, Attribute and Text from One Object
提问by Haiko Wick
I'm new into XML Serialization using .NET and after working with it for some time I'm quite fuzzled now. I can serialize elements with attributes containing other elements but how can I serialize something like
我是使用 .NET 进行 XML 序列化的新手,在使用它一段时间后,我现在很困惑。我可以序列化具有包含其他元素的属性的元素,但如何序列化类似
<myElement name="foo">bar</myElement>
I use a class for myElement with a XmlAttribute for the "name", but how to refer the value of the XML Element?
我为 myElement 使用了一个类,并为“名称”使用了 XmlAttribute,但是如何引用 XML 元素的值?
Thanks in advance.
提前致谢。
采纳答案by Marc Gravell
[XmlText]
, like so:
[XmlText]
,像这样:
using System;
using System.Xml.Serialization;
[Serializable, XmlRoot("myElement")]
public class MyType {
[XmlAttribute("name")]
public string Name {get;set;}
[XmlText]
public string Text {get;set;}
}
static class Program {
static void Main() {
new XmlSerializer(typeof(MyType)).Serialize(Console.Out,
new MyType { Name = "foo", Text = "bar" });
}
}