首页新闻找找看学习计划

代码如下,序列化出来也贴出来,但是希望父节点不要显示 <TestDy>,怎么才能不让它显示呢

0
悬赏园豆:20 [已解决问题] 解决于 2019-07-30 16:44

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();
    }
}

}

序列化的结果:

宇舟的主页 宇舟 | 初学一级 | 园豆:193
提问于:2019-07-27 18:29
< >
分享
最佳答案
1

可以自己定义一个对象,把你需要显示的属性写进去,然后再序列化试试看

收获园豆:20
兰茵 | 菜鸟二级 |园豆:448 | 2019-07-29 17:25

定义过了,还是没效果

宇舟 | 园豆:193 (初学一级) | 2019-07-30 11:04
其他回答(1)
0

已经换另外一种方法解决了

宇舟 | 园豆:193 (初学一级) | 2019-07-30 16:43
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册