noobed
noobed

Reputation: 1339

Add custom attributes when serializing Object to XML

is it possible to have a declarative markup for a C# object model in order to generate something like this:

 ...
 <locales>
    <add id="698" code="tr" name="Turkish" xsd:Transform="Insert"/>
    <add id="701" code="fr" name="French" />
 </locales>
 ....

instead of :

  ...
  <locales>
    <add d5p1:Transform="Insert" Locator="asdasdf" id="698" code="tr" name="Turkish" xmlns:d5p1="xdt" />
    <add id="701" code="fr" name="French" />
  </locales>
  ...

a simple example of my code is:

public class BaseTransformation
{
    [XmlAttribute]
    public string IsDefault { get; set; }

    [XmlAttribute(Namespace ="xdt")]
    public string Transform { get; set; }

    //[XmlAttribute("Locator")]
    public string Locator { get; set; }       
}


public class Locale : BaseTransformation
{
    [XmlAttribute("id")]
    public long ID { get; set; }

    [XmlAttribute("code")]
    public string Code { get; set; }

    [XmlAttribute("name")]
    public string Name { get; set; }
}


public class Languages
{
    [XmlArray(ElementName = "locales")]
    [XmlArrayItem(ElementName = "add")]
    public Locale[] Locales { get; set; }
}

I am trying to generate dynamically web.config transformations. d5p1:Transform="Insert" xmlns:d5p1="xdt" those two are not recognizable on build and does not apply the same functionality as intended.

Upvotes: 1

Views: 1082

Answers (1)

Dave M
Dave M

Reputation: 3033

You are confusing XML namespace prefixes with actual namespaces. In the Namespace property of XmlAttribute, you specify the full actual namespace, not the prefix you defined for that namespace. Namespace prefixes are arbitrary, and you can use whatever prefix you wish with a particular namespace using the xmlns attribute. The serialize thinks you are talking about a namespace called "xdt", not the actual namespace the "xdt" namespace typically refers to: "http://schemas.microsoft.com/XML-Document-Transform"

[XmlAttribute(Namespace = "http://schemas.microsoft.com/XML-Document-Transform")]
public string Transform { get; set; }

Upvotes: 2

Related Questions