开发者

How to deserialise Xml content to string

I'm using an XmlSerializer to deserialise a configuration file. I want to be able to fetch the child content of an Xml element into a string field. This child content can be xml itself.

A simple example:

public class Configuration
{
    [XmlAttribute]
    public string MyAttribute { get; set; }

    [XmlText]
    public string Content { get; set; }
开发者_Go百科}

I am trying to parse the following:

<Configuration MyAttribute="foo">
    <SomeOtherXml />
</Configuration>

I want the Content property to be set to "<SomeOtherXml />" but I can't seem to get this to work. I don't want to encapsulate the content inside a CDATA or similar.

Is this possible or do I need to manually handle the parsing of my configuration file?

Thanks


It is possible to use the XmlSerializer but does require manual parsing so it may not be worth it in the end.

There may be other and better ways to do this, but the way I found to do this is to have your Configuration class implement the IXmlSerializable interface.

public class Configuration : IXmlSerializable
{
    [XmlAttribute]
    public string MyAttribute { get; set; }

    [XmlText]
    public string Content { get; set; }

    public void ReadXml(XmlReader reader)
    {
        if(reader.NodeType == XmlNodeType.Element &&
           string.Equals("Configuration", reader.Name, StringComparison.OrdinalIgnoreCase))
        {
            MyAttribute = reader["MyAttribute"];
        }

        if(reader.Read() &&
           reader.NodeType == XmlNodeType.Element &&
           string.Equals("SomeOtherXml", reader.Name, StringComparison.OrdinalIgnoreCase))
        {
            Content = reader.ReadOUterXml();  //Content = "<SomeOtherXml />"
        }
    }

    public void WriteXml(XmlWriter writer) { }
    public XmlSchema GetSchema() { }
}

Hope this helps.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜