.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
david stephan
Gaurav Pal
Post New Web Links

XmlSerializer - how to define class to not generate attributes in root element?

Posted By:      Posted Date: August 28, 2010    Points: 0   Category :.NET Framework
Hi! I have simple class that I serialize to xml file: <?xml version="1.0" encoding="utf-8"?> <MyRootElement xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" Area="East">   <Products>     <SalesProduct Taxable="true">       <Name>Sofa</Name>     </SalesProduct>     <Product>       <Name>Television</Name>     </Product>   </Products> </MyRootElement> I don`t want have in xml file attributes xmlns:xsi and xmlns:xsd. How can I define class to not have these two attributes in xml file? I tried use XmlRoot attribute but there is no control for these two attributes. They are always generated. Regards

View Complete Post

More Related Resource Links

Can XmlSerializer add attributes to an element?

I'm using XmlSerializer to serialise a c# object into XML.public class Letter{        [XmlElement]        public String AccountNumber { get; set; }}which gives:<Letter><AccountNumber>12345678</AccountNumber></Letter>What I'd like to be able to do is to add a flag as an attribute to say if the particular data element is encrypted, so the XML comes out as:<Letter> <AccountNumber encrypted="true">=S2Hgd3$eDF</AccountNumber> </Letter>Is it possible to add this encrypted flag easily using the XmlSerializer? Thanks for any advice!

XML file - write attributes in root element


i have to write the following XML file using .net 2005.

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>

- <IMPORTFILE xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ARC_Carrier_Import.xsd">

No element name appears after using XmlSerializer on a class implementing ICollection



I have the following issue: after serilizing my class CounterInfoCollection that implements ICollection It doesn't come up with the correct xml. I know I may solve it by using List<> instead but now that i have implemented ICollection (I did that assuming List<T> were not supported as it stated on the msdn that Arrays of two kinds including List<T> were not supported) I would like to solve it using ICollection.

Here is an example of my xml and classes:


but i obviously want CounterInfoCollection to be CounterInfo and all items wrapped around CounterInfoCollection  like:

take for example the Classes CounterInfoCollection , CounterInfo and a Holder for holding the collection


public class CounterInfoCollection : ICollection
  private ArrayList counterInfoArray = new ArrayList();

  public CounterInfo this[int index]
    get { return (CounterInfo) counterInfoArray[index]; }

  public void CopyT

How do I generate proxy class for webservice with no WSDL published?

 Hello, I need to utilize following web service: https://www.icds.att.com/xmlrequest Service publishes 2 XML files (one for Request and another for Response) https://www.icds.att.com/schemas/XMLRequest.xsd and https://www.icds.att.com/schemas/XMLResponse.xsd. I generated classes for those manually, but my question is how do I actually utilize web service (generate proxy file) in this case. Do I have to code everything manually?

Add root xsi attributes to existing documents

I am looking for a way to perform a table update of an XML column containing strongly typed data. Recently, we modified our schema to include xmlns:xsi and xsi:schemaLocation. The thousands of documents already in the table, do not contain these new root element attributes, and I would like to add them. Sample old xml doc: <ROOT xmlns="http://www.xyz.com"><br/> <TAG>12345</TAG><br/> </ROOT>   Sample new xml doc: <ROOT xmlns="http://www.xyz.com"<br/> xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <br/> xsi:schemaLocation="http://www.xyzcom/schemas/A http://www.xyz.com/schemas/A/a.xsd"><br/> <TAG>12345</TAG><br/> </ROOT> Any thoughts or suggestions on how this might be accomplished?

Schema :relatioship expected & constant/fixed element cannot have attributes

I try to bullkload data from xml file to SQL database ,but I cannot figure out the problem.Please anyone help me .I'd really appreciate. the XML file :  <?xml version="1.0" encoding="UTF-8"?> <root>        <!-- ????? -->        <common>               <!-- UploadDataCenterID???????????????? -->               <UploadDataCenterID>XXXXXX</UploadDataCenterID>               <CreateTime>YYYY-MM-DD HH:MM:SS</CreateTime>        </common>        <data>                 <BuildGroup id="XXXXXXXXXX">                        <BuildGroupBaseInfo operation="N|U">                             <F_BuildGroupName>?????</F_BuildGroupName>                             <F_GroupAliasName>???????</F_GroupAliasName>                             <F_GroupDesc><![CDATA[?????]]></F_GroupDesc>                      </BuildGroupBaseInfo>                      <BuildGroupRelaInfo operation="N|U">                             <F_BuildID>XXXXXXXXXX</F_BuildID>                      </BuildGroupRelaInfo>               </BuildGroup>        </data> </root> then the XSD :<?xml version="1.0" encoding="UTF-8"?><xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xs

Root Element

Hi all, I decided to post in this forum as it doesn't directly relate to others...being a user-end question. I have a network of equally configured XP computers, and one Vista computer. For some reason, accessing certain ASP.NET sites on the Vista computer has just started getting server exceptions "Root element is missing". Normally I would write this off as a plain server-side error and wait for it to be fixed. However, the exception only occurs from one machine. All other machines load just fine. Caches are clear, computer rebooted, no malware or any non-default windows services running, etc. (Pure client/office machines)Any ASP.NET gurus know why this might be? Or how to fix it? Could it stem from an SSL cert/verification issue? (The error sites are using SSL).Thanks for your insight.

Can serialize but not deserialize class containing an xs:list attribute using XmlSerializer

I have a simple serializable class along the lines of: [Serializable] [XmlType] public class MyClass { [XmlAttribute("values")] public int[] Values { get; set; } } If I create an instance of this class with Values set to an empty collection the XmlSerializer class produces this output as expected: <?xml version="1.0" encoding="utf-16" ?> <MyClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" values="" /> However, deserializing this exact output throws a System.FormatException: Input string was not in a correct format. Shouldn't the XmlSerializer be able to deserialize this, since it produced the xml string in the first place?

Is it ok to make my own element attributes?

I want to make up some new attributes for elements like <div> and <a>. Those new attributes will be used to store data to be used by click handler jquery code.  Is that ok to do?  Is it supported by older browsers?   Testing on IE8 and Chrome, I am able to use jquery to store and recall in these made up attributes of a <DIV>element. ( I tried to use expression web super preview to test the code.  But apparantly, super preview does not run javascript. )thanks, <div id="div1" MadeUpAttr="abc"></div>     <script type="text/javascript">      $(document).ready(function ()      {        var s1 = $('#div1').attr('MadeUpAttr');        alert('MadeUpAttr: ' + s1);         $('#div1').attr('MadeUpAttr', 'efg');        var s2 = $('#div1').attr('MadeUpAttr');        alert('MadeUpAttr: ' + s2);      });    </script>  

Root element is missing error AFTER changing the List permission


I have an Infopath form that submits the data onto a SharePoint list. Everything works if the user has 'view, insert, edit, delete' access to the list. However, we dont want them to be able to delete and view the item so we gave this user group only 'insert' access. After doing so, they get the following error message:

The following DataObject either cannot be created or cannot be initialized:
The query cannot be run for the following DataObject: NameOfList
InfoPath cannot run the specified query.
The SOAP response indicates that the error occurred on the server:

Server was unable to process request. ==> The root element is missing. 

Anyone know if there's another way to solve this without granting the user group full access to the List?  I'm not an admin, I just normally request what type of permission to set on our sharepoint sites. 

Thanks for the help

MessageContract/XMLSerializer - Known Type not being named with its element name when passed as obje


Okay, I've just deleted my first post since I was having issues with editting a post with codeblocks.  Trying once more.

I'm new to WCF and I am trying to write a webservice that must follow a specific XML format.  Because of this, I found that I had to drop DataContractSerializer since I must be able to use attributes.  I now have the <XMLSerializerFormat> attribute on my servicecontract for this purpose and I have laid out the schema I need by using a Class with Public Properties and the <Serializable()> attribute where appropriate.  I have one service endpoint that has several different schemas that it may accept.  I have a base class with derived classes for this purpose.  This also works well from what I can see as the test client and webservice are talking to each other just fine.  However, the client that will be using the service is non-WCF and must have the elements named specifically in order to handle them.  The problem arises when the service is serializing the derived classes.  The structure of each class works perfectly, however, the name of the element is not the name of the element I have assigned it.  It is most likely because of the way that I pass the information back and forth to the service and the fact that I do not know what the object actually is when it is passed into or out o

Serialize a Class's properties as XML Attributes instead if Elements


Say you have a 3rd party provided assembly with a class like so:

User user = new User();

user.UserId = 1;
user.UserName = "johndoe";
user.Password = "password";


When serialized with the XmlSerializer it comes out something like this:


How to auto-generate object initzializer code according to any given class definition?



I think this is at least somewhat connected to reflection so I posted it here.

I work with WCF and Web Services right now. Of course I use the tools provided to generate code from the WSDL documents, hence, for every datatype, a corresponding class is generated. As the WS has loads of types with nested subtypes, I get about 80 usually small classes, only having a few members. In order to implement all that, I have to initialize the classes over and over again.

So I wonder, if there is no way, to use reflection to automatically generate  code (object inizializer) from the class definition, including all subclasses?

Ideal would be a snipped - so that I just enter the name of any random class and dynamically get the full initializer generated. Do snippets actually have the power to do that?

As this will save a lot of stupid typing, I also wonder, if there aren't already any tools, snippets or widgets that do this? I assumed that is is something many programmers might need, but google did not show anything like it.

Thank you very much!

Add class before the element



How to add a class before a given element?

The code doesn't add a class but instead add a new element. Sad

    <script type="text/javascript">

        $(function () {
            $('ul li a').click(function () {
                var inst = $(this);
                var beforeElement = inst.before('ul');



    <form id="form1" runat="server">
    <ul class="first"> <!--add new class for this ul after a click of the link Programming-->

Generate XSD file from Class



If anyone knows a link to some documentation regarding generating xsd file from a class (the same as xsd.exe does), ie: how it works, what it uses, the concept / relation behind this conversion. I've tried to search the web and all i was pointed to was xsd.exe tool which doesn't work for my dll/class.


Dynamically Generate a WCF Proxy class at runtime and Callling web methods via reflection



I'm busy writing an application where the user will have to specify the location of a ?wsdl file for asmx and/or svc type services.

My application will have to :

1. Deduce from the wsdl what methods (with parameters and return types) are available on the service.

2. Provide a way to either generate a Proxy class in memory to execute methods against with e.g: Reflection

    for instanse : genericProxy.Invoke("HelloWorldMethod",parameter1,parameter2);

    I want to avoid using something like this : notSoGenericProxy.HelloWorldMethod(parameter1,parameter2); seeing that my application will have no 

    idea what service it will have to work with at runtime.

Is there a way to achieve this?

Thank you for any help in advance!

Serializing attributes at the message root level


Hi All,

I rarely find the need to post to a forum, but I have encountered an issue that I just can't resolve. I need to send and receive a message via WCF with the following structure:

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Header />
    <SignRequest RequestID="_1234" Protocol="urn:protocol">

I can use a MessageContract to control the root element (the SignRequest) but attempting to add Attributes (as per http://msdn.microsoft.com/en-us/library/ms733901(v=VS.90).aspx ) causes the XmlSerializer to throw an exception complaining that I can't use the XmlAttribute attribute. I can use the XmlSerializer in it's raw form but then I don't seem to have control over the root element (a 'wrapping' element with the method name is added).

At this stage, I'd be happy to use message contracts, the XmlSerializer or any combination of the above! If anyone has any pointers, I would very much appreciate it.



ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend