Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 962311
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 16, 20262026-05-16T01:29:14+00:00 2026-05-16T01:29:14+00:00

I have a WCF service and cannot use DataContracts since I need more control

  • 0

I have a WCF service and cannot use DataContracts since I need more control over the XML received and sent to this service. As such, I use XmlRoot, and XmlElement… the problem I’m running into now is that my class that the receiving xml gets deserialized into and the serialized response both need to have the same root name, and when I try to set both of those classes with:

[XmlRoot(ElementName = "myRoot")] 

I get an error saying that the root name was already used. Is there a simple workaround for this? I tried putting my response class in a separate namespace but that didn’t appear to work.

If some of the variables aren’t set in my response class that gets serialized then I don’t them to get serialized and returned in the response… is there an option I’m missing to do this… I was able to do this with a DataContract, but cant figure it out with XmlElements

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-16T01:29:15+00:00Added an answer on May 16, 2026 at 1:29 am

    One way to achieve this is to intercept the XML response and change the root element name to something unique before it is deserialized. This can be done pretty easily with a custom IClientMessageFormatter and an associated attribute on the operation.

    I just wrote this up, so “wet paint” and all, but here is what that looks like:

    /// <summary>
    /// An operation attribute that changes the XML root name in responses
    /// </summary>
    /// <example>
    ///     
    /// [ServiceContract]
    /// [XmlSerializerFormat]
    /// public interface IRedBlueServiceApi
    /// {
    ///     [OperationContract]
    ///     [WebGet(...)]
    ///     [XmlChangeRoot("RedResponse")]
    ///     RedResponse GetRed();
    ///
    ///     [OperationContract]
    ///     [WebGet(...)]
    ///     [XmlChangeRoot("BlueResponse")]
    ///     BlueResponse GetBlue();
    /// }
    /// 
    /// [XmlRoot("RedResponse")]
    /// public class RedResponse 
    /// {...}
    /// 
    /// [XmlRoot("BlueResponse")]
    /// public class BlueResponse 
    /// {...}
    /// </example>
    [DefaultProperty("NewRootElementName")]
    public class XmlChangeRootAttribute : Attribute, IOperationBehavior
    {
        public XmlChangeRootAttribute(string newRootElementName)
        {
            NewRootElementName = newRootElementName;
        }
    
        public string NewRootElementName { get; set; }
    
        #region IOperationBehavior Members
    
        public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation)
        {
            // Inject our xml root changer into the client request/response pipeline
            clientOperation.Formatter = new XmlRootChangeFormatter(clientOperation.Formatter, NewRootElementName);
        }
    
        #endregion
    
        #region Unrelated Overrides
    
        public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)
        {
        }
    
        public void AddBindingParameters(OperationDescription operationDescription,
                                         BindingParameterCollection bindingParameters)
        {
        }
    
        public void Validate(OperationDescription operationDescription)
        {
        }
    
        #endregion
    }
    
    /// <summary>
    /// A simple wrapper around an existing IClientMessageFormatter
    /// that alters the XML root name before passing it along
    /// </summary>
    public class XmlRootChangeFormatter : IClientMessageFormatter
    {
        private readonly IClientMessageFormatter _innerFormatter;
        private readonly string _newRootElementName;
    
        public XmlRootChangeFormatter(IClientMessageFormatter innerFormatter, string newRootElementName)
        {
            if (innerFormatter == null)
                throw new ArgumentNullException("innerFormatter");
    
            if (String.IsNullOrEmpty(newRootElementName))
                throw new ArgumentException("newRootElementName is null or empty");
    
            _innerFormatter = innerFormatter;
            _newRootElementName = newRootElementName;
        }
    
        #region IClientMessageFormatter Members
    
        public Message SerializeRequest(MessageVersion messageVersion, object[] parameters)
        {
            return _innerFormatter.SerializeRequest(messageVersion, parameters);
        }
    
        public object DeserializeReply(Message message, object[] parameters)
        {
            if (!message.IsEmpty)
            {
                var doc = XDocument.Load(message.GetReaderAtBodyContents());
    
                if (doc.Root == null)
                    throw new SerializationException("Could not find root in WCF messasge " + message);
    
                // Change the root element name 
                doc.Root.Name = _newRootElementName;
    
                // Create a new 'duplicate' message with the modified XML
                var modifiedReply = Message.CreateMessage(message.Version, null, doc.CreateReader());
                modifiedReply.Headers.CopyHeadersFrom(message.Headers);
                modifiedReply.Properties.CopyProperties(message.Properties);
    
                message = modifiedReply;
            }
    
            return _innerFormatter.DeserializeReply(message, parameters);
        }
    
        #endregion
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a WCF Data Service. I cannot use this format (Long story, proxy
I have a wcf service defined like this: [OperationContract] [WebInvoke(Method = POST, ResponseFormat =
I have a WCF service that I need to call in a ASP.NET web
I have received few WSDLs and XSD defining a service that I need to
I have a WCF which has very few light methods. This service is used
I have an IIS hosted WCF service with single-call behavior. I use Fluent NH
I have been tasked with implementing a WCF service in VB.NET. This WCF service
I have developed an ASP.NET application that includes a WCF service. This service needs
I have a WCF Service hosted on IIS. For business reason I cannot post
I have a WCF service that is exposed. In terms of security i need

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.