我需要生成一个遵循此特定的XML文档
<productName locale="en_GB">Name</productName>
但是使用XMLSeralization我得到以下
<productName locale="en_GB">
<Name>Name</Name>
</productName>
我的C#代码是这样的:
[Serializable]
public class productName
{
public productName()
{
}
public string Name;
[XmlAttribute]
public string locale;
}
XmlAttribute是在正确的位置显示语言环境所需的,但我无法弄清楚如何正确导出名称字段。
有没有人有想法?
由于
编辑:
这是生成XML的代码
public static class XMLSerialize
{
public static void SerializeToXml<T>(string file, T value)
{
var serializer = new XmlSerializer(typeof(T));
using (var writer = XmlWriter.Create(file))
serializer.Serialize(writer, value);
}
public static T DeserializeFromXML<T>(string file)
{
XmlSerializer deserializer = new XmlSerializer(typeof(T));
TextReader textReader = new StreamReader(file);
T result;
result = (T)deserializer.Deserialize(textReader);
textReader.Close();
return result;
}
}
答案 0 :(得分:5)
不是将 Name 指定为元素,而是通过添加 [XmlText] 属性
将其指定为文本值[XmlText]
public string Value { get; set; }
答案 1 :(得分:2)
这不仅包含对您问题的直接回答,而且更多地是对未来如何解决类似问题的间接回答。
从你的xml开始,用xml完全按照自己的意愿编写你的xml并从那里开始,如下所示:
// assuming data.xml contains the xml as you'd like it
> xsd.exe data.xml // will generate data.xsd, ie xsd-descriptor
> xsd.exe data.xsd /classes // will generate data.cs, ie c# classes
> notepad.exe data.cs // have a look at data.cs with your favorite editor
现在只看一下data.cs,这将包含大量的属性和东西,命名空间可能是错误的,但至少你知道如何解决你的特定xml问题。
直接的答案是使用给定属性上的XmlTextAttribute,最好命名为Value
,因为这是我迄今为止看到的惯例。
[Serializable]
public class productName {
public productName() { }
[XmlText]
public string Value {get; set;}
[XmlAttribute]
public string locale {get; set;}
}