1

I need to change the xml root tag name from "string" to "TramaOutput". How to achieve this

public string ToXml() 
    { 
        XElement element = new XElement("TramaOutput", 
        new XElement("Artist", "bla"), 
        new XElement("Title", "Foo")); 
        return Convert.ToString(element);
    }

For this the output is:

<string>
    <TramaOutput>
        <Artist>bla</Artist>
        <Title>Foo</Title>
    </TramaOutput>
</string>

In the below mentioned code I am getting an error like "Cannot use wildcards at the top level of a schema."

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Xml.Linq;

namespace WebApplication1
{
    /// <summary>
    /// Summary description for WebService1
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class WebService1 : System.Web.Services.WebService
    {

        [WebMethod]
        public XElement getXl()
        {
            XElement element = new XElement("Root",new XElement("BookId",1),new XElement("BookId",2));

            return element;
        }
    }
}
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
Vignesh
  • 1,458
  • 12
  • 31
  • 59

2 Answers2

4

Your code generates correct xml, there is no error:

<TramaOutput>
    <Artist>bla</Artist>
    <Title>Foo</Title>
</TramaOutput>

You see <string> element, because you are sending this xml as a string data type over the network. I.e. you receive string with content of your xml.


More examples - if you will send "42" string, you'll see

<string>42</string>

How to solve your problem? Create following class:

public class TramaOutput
{
    public string Artist { get; set; }
    public string Title { get; set; }
}

And return instance of it from your web service:

[WebMethod]
public TramaOutput GetArtist()
{
    return new TramaOutput {Artist = "bla", Title = "foo"};
}

Object will be serialized into your xml:

<TramaOutput><Artist>bla</Artist><Title>foo</Title></TramaOutput>

You don't need to build xml manually!


If you want to control process of serialization, you can use xml attributes. Apply attributes to your class and it's members, like this:

[XmlAttribute("artist")]
public string Artist { get; set; }

That will serialize property into attribute:

<TramaOutput artist="bla"><Title>foo</Title></TramaOutput>
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
1

I checked it under .net 4.5 Both

Convert.ToString(element);
element.ToString();

Are all return

<TramaOutput>
    <Artist>bla</Artist>
    <Title>Foo</Title>
</TramaOutput>

What's .NET version and XML.Linq version you are using now?

Yemol
  • 29
  • 3