XmlSerializer: serializing a class property as an attribute of a custom subitem

I use XmlSerializer. My class:

[Serializable]
[XmlRoot(ElementName="MyClass")]
public class MyClass
{
    public string Value;
}

I would like to serialize it so that it Valueends as an attribute of a sub-element named (for example) “Text”.

Desired Result:

<MyClass>
    <Text Value="3"/>
</MyClass>

But NOT (which would be a consequence of labeling the value as XmlAttribute)

<MyClass Value="3">
</MyClass>

AND NOT (which would be the result of marking the value as XmlElement):

<MyClass>
    <Value>3</Value>
</MyClass>

How do I achieve this?

I know that I could change the type Valuefrom a string to another serializable custom class.

Unfortunately, I have many such properties, so I need to create dozens of tiny classes.

Is there a faster solution?


EDIT:

In response to your comments:

  • , "". .

  • XML:

    <visibility>
        <site visible="yes"/>
        <comparator visible="no"/>
        <expiration days="7"/>
        <comment>blahblahblah</comment>
    <visibility>
    
  • :

!

[XmlRoot(ElementName="Visibility")]
public class Visibility
{
    [XPath("/site@visible")] // if only this was possible!
    public string OnSite
    {
        get { return SiteVisible ? "yes" : "no"; }
    }

    [XPath("/comparator@visible")] // as above...
    public string InComparator
    {
        get { return ComparatorVisible ? "yes" : "no"; }
    }

    [XmlIgnore]
    public bool SiteVisible;
    [XmlIgnore]
    public bool ComparatorVisible;

    [XPath("/expiration@days")] // as above...
    public int ExpiresAfterDays; 

    [XmlElement("comment")] // this is easy
    public string Comment;
}
+5
3

Value , . XmlElement(ElementName="Text") Value, , :

<MyClass> 
    <Text>3</Text> 
</MyClass> 

: XSLT: xml .Net xml.

XslTransform myXslTransform = new XslTransform();
myXslTransform.Load(xsltDoc);
myXslTransform.Transform(sourceDoc, resultDoc);

:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/">
    <root>
        <xsl:apply-templates/>
    </root>
    </xsl:template>
    <xsl:template match="MyClass">
        <MyClass>
            <Text>
               <xsl:attribute name="Value">
                    <xsl:value-of select="Text"/>
               </xsl:attribute>
            </Text>
        </MyClass>
    </xsl:template>
</xsl:stylesheet>
+4

IXmlSerializable, :

[XmlRoot("visibility")]
public class Visibility : IXmlSerializable
{
    public string Site;
    public string Comparator;
    public int Expiration;
    public string Comment;

    public XmlSchema GetSchema()
    {
        throw new NotImplementedException();
    }

    public void ReadXml(XmlReader reader)
    {
        // implement me if you want to deserialize too.
        throw new NotImplementedException();
    }

    public void WriteXml(XmlWriter writer)
    {
        WriteProperty(writer, "site", "visible", Site);
        WriteProperty(writer, "comparator ", "visible", Comparator);
        WriteProperty(writer, "expiration ", "days", Expiration);

        if (!string.IsNullOrEmpty(Comment))
        {
            writer.WriteElementString("comment", Comment);
        }
    }

    private void WriteProperty<T>(XmlWriter writer, string elementName, string attibuteName, T value)
    {
        if (value != null)
        {
            writer.WriteStartElement(elementName);
            writer.WriteAttributeString(attibuteName, value.ToString());
            writer.WriteEndElement();
        }
    }
}

, , , .

- , xml .

+4

. , .NET XmlSerialization ( , !). .

, ( , , ) XmlSerializer , , , .

- :

    /// <remarks>
    /// (angle brackets replaced with round ones to avoid confusing the XML-based documentation comments format)
    /// 
    /// Let input XML be:
    /// 
    ///     (root)
    ///         (days)3(/days)
    ///     (/root)
    ///     
    /// Calling Reposition on this input with mappings argument being:
    ///     (key) "days"
    ///     (value) { "time", "days" }
    ///     
    /// Returns:
    /// (root)
    ///     (time days="3" /)
    /// (/root)
    /// </remarks>        
    static XElement Reposition(XElement input, KeyValuePair<string, string[]>[] mappings)
    {
        var result = new XElement(input);
        foreach (var mapping in mappings)
        {
            var element = result.Element(mapping.Key);
            if (element == null)
            {
                continue;
            }
            var value = element.Value;
            element.Remove();

            var insertAt = result;
            foreach (var breadcrumb in mapping.Value)
            {
                if (breadcrumb == mapping.Value.Last())
                {
                    insertAt.Add(new XAttribute(breadcrumb, value));
                }
                else
                {
                    insertAt.Add(new XElement(breadcrumb));
                    insertAt = insertAt.Element(breadcrumb);
                }
            }
        }
        return result;
    }

, ( XPath, , , : . ), .

/ ?

(/ XML ), XML , , , .

( "", XPath ).

0

All Articles