1

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

2 に答える 2

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

そして、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; }

これにより、プロパティが属性にシリアル化されます。

<TramaOutput artist="bla"><Title>foo</Title></TramaOutput>
于 2013-06-14T07:44:16.397 に答える
1

.net 4.5 両方で確認しました

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

全員復帰です

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

現在使用している .NET のバージョンと XML.Linq のバージョンは何ですか?

于 2013-06-14T07:48:44.757 に答える