简体   繁体   English

XML序列化问题 - 如何从一个对象序列化元素,属性和文本

[英]XML Serialization question - How to Serialize Element, Attribute and Text from One Object

I'm new into XML Serialization using .NET and after working with it for some time I'm quite fuzzled now. 我是使用.NET进行XML序列化的新手,在使用它一段时间之后我现在非常费力。 I can serialize elements with attributes containing other elements but how can I serialize something like 我可以使用包含其他元素的属性来序列化元素,但是如何序列化类似的元素

<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的“name”类,但是如何引用XML Element的值?

Thanks in advance. 提前致谢。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM