Mat*_*ley 3 .net xml xml-serialization
我有以下代码:
public class Foo {}
static class Program {
[XmlElement("foo")] // Ignored :(
static public List<Foo> MyFoos { get; private set; }
public static void Main() {
MyFoos.Add(new Foo());
MyFoos.Add(new Foo());
XmlSerializer configSerializer =
new XmlSerializer(typeof(List<Foo>), new XmlRootAttribute("foos"));
using (TextWriter w = new StreamWriter("test.xml"))
{
s.Serialize(w, MyFoos);
}
}
}
Run Code Online (Sandbox Code Playgroud)
其中生成以下XML文件:
<?xml version="1.0" encoding="utf-8"?>
<foos xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Foo />
<Foo />
</foos>
Run Code Online (Sandbox Code Playgroud)
我真正想要的是Foo标记为的元素foo,而不是......我意识到这主要是装饰性的,但它符合XML中通常被认为是正常的.
JP *_*oto 11
如果你直接设置元素名称它应该工作...
[XmlElement( ElementName = "foo" )]
Run Code Online (Sandbox Code Playgroud)
见这里的例子.它必须是静态的吗?如果是这样,这没有帮助,但这很好(添加了每条评论的往返)......
namespace TestSerial
{
public class Foo
{
public int Value
{
get;
set;
}
}
public class SerializeMe
{
private List<Foo> _foos = new List<Foo>();
public SerializeMe()
{
}
[XmlElement("foo")]
public List<Foo> MyFoos { get { return _foos; } }
}
class Program
{
static void Main(string[] args)
{
var fs = new SerializeMe();
fs.MyFoos.Add(new Foo() { Value = 1 });
fs.MyFoos.Add(new Foo() { Value = 2 });
var s = new XmlSerializer(typeof(SerializeMe), new XmlRootAttribute("foos"));
using (var w = new StreamWriter(@"c:\temp\test.xml"))
{
s.Serialize(w, fs);
}
using (var r = new StreamReader(@"c:\temp\test.xml"))
{
var o = s.Deserialize(r);
var fs2 = (SerializeMe)o;
fs2.MyFoos.Select(f => f.Value).ToList().ForEach(Console.WriteLine);
}
Console.ReadLine();
}
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:(马修,OP)
我的最终解决方案,我认为上述的改进是:
public class Foo {}
[XmlRoot("foos")]
public class FooList
{
public FooList() { Foos = new List<Foo>(); }
[XmlElement("foo")]
public List<Foo> Foos { get; set; }
}
static class Program
{
static private FooList _foos = new FooList();
static public List<Foo> MyFoos { get { return _foos; } }
public static void Main()
{
MyFoos.Add(new Foo());
MyFoos.Add(new Foo());
XmlSerializer configSerializer =
new XmlSerializer(typeof(FooList));
using (TextReader r = new StreamReader("test.xml"))
{
_foos = (FooList)configSerializer.Deserialize(r);
}
using (TextWriter w = new StreamWriter("test.xml"))
{
configSerializer.Serialize(w, _foos);
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7063 次 |
| 最近记录: |