【问题标题】:How to show custom XML tags instead of string tag如何显示自定义 XML 标签而不是字符串标签
【发布时间】:2014-07-21 20:52:05
【问题描述】:

我有一个 RESTFUL API 服务,它返回具有唯一 ID 号的位置的城市、州、邮编等。在我获取数据的函数中,我返回了一个名为“List”的数组。例如,数组结果为<string>Kansas City</string>

我怎样才能拥有像<City>Kansas City</City> <State>MO</State>. 这样的客户标签?

我在函数中的代码的一个sn-p是:

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 格式返回结果

【问题讨论】:

  • 那么您如何从 API 返回数据?
  • 您需要实现一个类来封装您要通过网络发送的所有数据,然后使用 DataContract 或 XmlSerializer 发出所需的 XML 输出。

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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多