开发者

How can I add child elements in XML inside particular parent node?

开发者 https://www.devze.com 2023-01-07 17:15 出处:网络
I have serialized a following log class: [Serializable] [XmlRoot(\"Log\")] public class Log { [XmlElement(\"ErrorLog\")]

I have serialized a following log class:

[Serializable]
[XmlRoot("Log")]
public class Log
{
    [XmlElement("ErrorLog")]
    public ErrorLog Error { get; set; }


    [XmlElement("MessageLog")]
    public MessageLog Message { get; set; }
}

public class ErrorLog
{
    [XmlElement("ErrorMessage")]
    public string ErrorMessage { get; set; }

    [XmlElement("Module")]
    public string Module { get; set; }

    [XmlElement("Component")]
    public string C开发者_开发知识库omponent { get; set; }
}

public class MessageLog
{
    [XmlElement("Message")]
    public string Message { get; set; }

    [XmlElement("Module")]
    public string Module { get; set; }
}

I am serializing the above Log class in an XML File as:

abc TestClient

abc TestClient DataAccessLayer

Is it possible that I add all elements whether they are ErrorLogs or MessageLogs inside a single root like: abc TestClient DataAccessLayer abc TestClient


You can create BaseLog class and declare List<BaseLog> inside Log. MesageLog and ErrorLog should inherit from BaseLog

By the way, there is no need to apply XmlElement attribute to properties if XmlElement has the same value as property name. Please invest some time for loggers, such as log4net

I suppose keeping log as XML is not a best practice (use plain text files instead). As application can crash every second you should flush log file nearly every time new message appeared. It's easy with plain files (when you write bytes after the last ones) and hard with xml, as you have to write before the closing tag.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号