简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM