如何显示自定义XML标记而不是字符串标记

时间:2014-07-21 20:52:06

标签: c# web-services tags restful-url

我有一个RESTFUL API服务,它返回具有唯一ID号的位置的City,State,Zip等。在我获取数据的函数中,我返回一个名为“List”的数组。例如,数组导致<string>Kansas City</string>

我如何拥有<City>Kansas City</City> <State>MO</State>.等客户代码?

我在函数中的代码片段是:

string [] List = new string [7];
            List[0]= City;
            List[1]= County;
            List[2]= State;
            List[3]=Postal;
            List[4]=isDefaultLocation;
            List[5]=locationId;
            List[6]=AtlasKey;

            return List;

使用example.com/locations/id/10000

以XML格式返回结果

1 个答案:

答案 0 :(得分:0)

您必须创建自己的类,例如:

using System.Xml.Serialization; // XML serialization requires this namespace
using System.IO;

[XmlRootAttribute("Info")]
public class Info
{
    // static constructor will create serializer instance
    static Info()
    {
        Serializer = new XmlSerializer(typeof(Info));
    }        

    // here write constructor based on array of strings

    // this method will serialize current object to stream
    public void SerializeToXml(Stream stream)
    {
        Serializer.Serialize(stream, this);
    }

    // this static method will deserialize object from stream
    public static Info DeserializeFromXml(Stream stream)
    {
        return Serializer.Deserialize(stream) as Info;
    }

    [XmlElement("City")] // use XmlElement, not XmlAttribute
    public string City
    {
        get;
        set;
    }

    // here you can add your other fields like above

    [XmlIgnore] // we want to be sure that this field won't be serialized
    private static XmlSerializer Serializer
    {
        get;
        set;
    }
}