如何在xml中更改根标记名称

时间:2013-06-14 07:33:28

标签: c# asp.net xml web-services

我需要将xml根标记名称从“string”更改为“TramaOutput”。如何实现这个

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

为此,输出为:

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

在下面提到的代码中,我收到的错误如“无法在架构的顶层使用通配符”。

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;
        }
    }
}

2 个答案:

答案 0 :(得分:4)

您的代码生成正确的xml,没有错误:

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

您会看到<string>元素,因为您要通过网络将此xml作为字符串数据类型发送。即您收到包含xml内容的字符串。


更多示例 - 如果您要发送"42"字符串,则会看到

<string>42</string>

如何解决您的问题?创建以下类:

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

从您的网络服务返回它的实例:

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

对象将序列化到您的xml:

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

您无需手动构建xml!


如果要控制序列化过程,可以使用xml attributes。将属性应用于您的类及其成员,如下所示:

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

这会将属性序列化为属性:

<TramaOutput artist="bla"><Title>foo</Title></TramaOutput>

答案 1 :(得分:1)

我在.net 4.5下查了两下

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

全部返回

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

您现在使用的.NET版本和XML.Linq版本是什么?