序列化的类C#类为XML的属性和单个值 [英] Serialize a C# class to XML with attributes and a single value for the class

查看:520
本文介绍了序列化的类C#类为XML的属性和单个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用C#和XmlSerializer的序列化以下类:

I am using C# and XmlSerializer to serialize the following class:

public class Title
{
    [XmlAttribute("id")]
    public int Id { get; set; }

    public string Value { get; set; }
}



我想这个序列化到下列XML格式:

I would like this to serialize to the following XML format:

<Title id="123">Some Title Value</Title>

在换句话说,我想Value属性是在XML中的标题元素的值文件。我似乎无法找到任何方式来做到这一点没有实现我自己的XML序列化,这是我想避免的。 。任何帮助,将不胜感激。

In other words, I would like the Value property to be the value of the Title element in the XML file. I can't seem to find any way to do this without implementing my own XML serializer, which I would like to avoid. Any help would be appreciated.

推荐答案

尝试使用 [XMLTEXT]

public class Title
{
  [XmlAttribute("id")]
  public int Id { get; set; }

  [XmlText]
  public string Value { get; set; }
}

下面就是我得到的(但我并没有花很多的时间。扭捏的XmlWriter,所以你得到了一堆噪声的命名空间的方式,等等:

Here's what I get (but I didn't spend a lot of time tweaking the XmlWriter, so you get a bunch of noise in the way of namespaces, etc.:

<?xml version="1.0" encoding="utf-16"?>
<Title xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:xsd="http://www.w3.org/2001/XMLSchema"
       id="123"
       >Grand Poobah</Title>

这篇关于序列化的类C#类为XML的属性和单个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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