从类生成 XML [英] Generate XML from a class

查看:31
本文介绍了从类生成 XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从一个类构建以下 XML 节点.

I want to build the following XML node from a class.

<Foo id="bar">some value</Foo>

我的类定义应该如何?

class Foo
{
   public string Value {set;get;}
   public string id{set;get;}
}

我认为我应该为这些属性添加一些 XML 属性,但不确定它们是什么.

I believe i should put some XML attributes to these properties but not sure what they are.

推荐答案

查看 System.Xml.Serialization 命名空间下的属性.在您的情况下,该类应类似于下面的代码.

Take a look at the attributes under the System.Xml.Serialization namespace for that. In your case, the class should look like the code below.

public class StackOverflow_8281703
{
    [XmlType(Namespace = "")]
    public class Foo
    {
        [XmlText]
        public string Value { set; get; }
        [XmlAttribute]
        public string id { set; get; }
    }
    public static void Test()
    {
        MemoryStream ms = new MemoryStream();
        XmlSerializer xs = new XmlSerializer(typeof(Foo));
        Foo foo = new Foo { id = "bar", Value = "some value" };
        xs.Serialize(ms, foo);
        Console.WriteLine(Encoding.UTF8.GetString(ms.ToArray()));
    }
}

更新:添加了用于序列化类型的代码.

Update: added code to serialize the type.

这篇关于从类生成 XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆