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

本文关键字:何更改 xml | 更新日期: 2023-09-27 18:18:26

我需要将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;
        }
    }
}

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

您的代码生成正确的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; }
}

并从您的web服务返回它的实例:

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

对象将被序列化到xml:

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

您不需要手动构建xml !


如果你想控制序列化过程,你可以使用xml属性。对类及其成员应用属性,如下所示:

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

将属性序列化为attribute:

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

我在。net 4.5下检查了它

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

都返回

<TramaOutput>
    <Artist>bla</Artist>
    <Title>Foo</Title>
</TramaOutput>
. net版本和XML是什么?您现在使用的是Linq版本?