using System.Diagnostics;
using System.Text;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.IO;
using System.Text.RegularExpressions;
using System.Dynamic;
using System.Runtime.Serialization;
namespace ConsoleApplication3
{
public class AllTest
{
[XmlElement]
public List<Test> Test { get; set; }
public AllTest() { }
}
public class Test
{
[XmlAttribute]
public string id;
[XmlElement]
public List<TestDy> TestDy { get; set; }
public Test() { }
public Test(string id)
{
this.id = id;
}
}
public class TestDy : DynamicObject, IXmlSerializable
{
[XmlAttribute]
public string Sid { get; set; }
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
string name = binder.Name.ToLower();
bool exist = Dict.TryGetValue(name, out result);
if (!exist)
{
// 不存在,默认空
result = null;
}
return true;
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
Dict[binder.Name.ToLower()] = value;
return true;
}
Dictionary<string, object> Dict = new Dictionary<string, object>();
public XmlSchema GetSchema()
{
return (null);
}
public void ReadXml(XmlReader reader)
{
Sid = reader.ReadString();
}
public void WriteXml(XmlWriter writer)
{
writer.WriteStartElement("Sid");
writer.WriteAttributeString("id", Sid.ToString());
foreach (var item in Dict)
{
writer.WriteAttributeString(item.Key, item.Value.ToString());
}
writer.WriteEndElement();
}
public TestDy() { }
public TestDy(string sid)
{
this.Sid = sid;
}
}
public class Program
{
static void Main(string[] args)
{
AllTest alltest = new AllTest();
alltest.Test = new List<Test>();
alltest.Test.Add(new Test());
alltest.Test[0].TestDy = new List<TestDy>();
dynamic dy = new TestDy();
alltest.Test[0].TestDy.Add(dy);
dy.Sid = "9527";
dy.属性1 = "123";
dy.属性2 = "456";
dy.属性3 = "789";
TextWriter writer = new StreamWriter("C:\\Users\\LYY\\Desktop\\alltest.xml");
XmlSerializer serializer = new XmlSerializer(alltest.GetType());
serializer.Serialize(writer, alltest);
writer.Close();
}
}
}
序列化的结果:
可以自己定义一个对象,把你需要显示的属性写进去,然后再序列化试试看
定义过了,还是没效果
已经换另外一种方法解决了