簡體   English   中英

如何對具有相同名稱的多個屬性的XML API響應進行脫鹽處理

[英]How to Desalinize XML API Response with Multiple Attributes with same name

我想閱讀此Web API的XML回復我想反序列化它,但遇到錯誤我已經看過很多關於該主題的紀錄片,但是我無法解決

<ArrayOfServiceAreas xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns="http://tempuri.org/">
<ServiceAreas>
<City>
<string>ABDUL HAKIM /TULAMBA</string>
<string>ABOTTABAD</string>
<string>AHMED PUR EAST</string>
<string>ALI PUR</string>
<string>ALI PUR CHATTA</string>
<string>ARIF WALA</string>
<string>ATTOCK</string>
<string>BADIN</string>
<string>BAGH (AJK)</string>
<string>BANU</string>
<string>BAT KHELA</string>
<string>BAWALNAGAR</string>
<string>BHAI PHERU</string>
<string>BHAKKAR</string>
<string>BHALWAL</string>
<string>BHAWALPUR</string>
<string>BUREWALA</string>
<string>CHAKWAL</string>
<string>CHAMAN</string>
<string>CHARSADA</string>
<string>CHICHAWATNI</string>
<string>CHINNIOT</string>
<string>CHISTIAN</string>
<string>CHITRAL</string>
<string>D.G. KHAN</string>
<string>D.I. KHAN</string>
<string>DADU</string>
<string>DADYAL (AJK)</string>
<string>DALBANDIN</string>
<string>DARA ADAM KHEL</string>
<string>DARGAI</string>
</City>
</ServiceAreas>
</ArrayOfServiceAreas>

在C#中,我創建了下面給出的兩個類以反序列化對象

[Serializable]
public class City
{
    [System.Xml.Serialization.XmlElement("string")]
    public string[] String { get; set; }
}

[Serializable()]
[System.Xml.Serialization.XmlRoot("ArrayOfServiceAreas")]
public class ArrayOfServiceAreas
{

    [XmlArray("ServiceAreas")]
    [XmlArrayItem("City", typeof(City))]
    public City[] City { get; set; }
}

這是我使用XML Serializer調用上述類的控制器

public ActionResult City()
    {
        string Perameters = $"username={"myusername"}&password={"mypassword"}&AccountNo={"somenumber"}";
        string u = "http://mraabta.mulphico.pk/mnpconsignments/pushtomnp.asmx/Get_Cities?"+Perameters;
        var client = new RestClient(u);
        var request = new RestRequest(Method.GET);
        request.RequestFormat = DataFormat.Xml;
        request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
        var responce = client.Execute(request);
        //var r = JsonConvert.DeserializeObject<dynamic>(responce.Content);
        System.IO.StringReader SR = new System.IO.StringReader(responce.Content.ToString());

        XmlSerializer serializer = new XmlSerializer(typeof(MNP_Plus.Dserializer.MNPCities.ArrayOfServiceAreas));
        MNP_Plus.Dserializer.MNPCities.ArrayOfServiceAreas List = (MNP_Plus.Dserializer.MNPCities.ArrayOfServiceAreas)serializer.Deserialize(SR);

        return View();
    }

響應內容以我想閱讀的XML形式在上面給出。 它給出了錯誤XML文檔(2,2)中存在錯誤。 我該如何解決。

沒有及時找到問題的解決方案,所以我以老式的方式做了。如果其他人陷入混亂,那么解決方案可能是

private List<string> GetCities(string Responce)
    {
        List<string> list = new List<string>();
        bool Collection = false;
        string item = "";
        int count = 0;
        foreach (char i in Responce)
        {
            if (Collection)
            {
                if(i == '<') { list.Add(item); item = ""; Collection = false; }
                else { item = item + i; }
            }
            if (count == 0) { if (i == '<') { count = 1; } }
            else if (count == 1) { if (i == 's') { count = 2; } else { count = 0; } }
            else if (count == 2) { if (i == 't') { count = 3; } else { count = 0; } }
            else if (count == 3) { if (i == 'r') { count = 4; } else { count = 0; } }
            else if (count == 4) { if (i == 'i') { count = 5; } else { count = 0; } }
            else if (count == 5) { if (i == 'n') { count = 6; } else { count = 0; } }
            else if (count == 6) { if (i == 'g') { count = 7; } else { count = 0; } }
            else if (count == 7) { if (i == '>') { Collection = true; } count = 0; }
        }
        return list;
    }

根據您的問題進行更改。

問題出在您的映射類中。 為了使您的生活更輕松,您可以使用在線xml2csharp在線工具來獲取適當的POCO。 這里

他們應該看起來像這樣:

[XmlRoot(ElementName = "City", Namespace = "http://tempuri.org/")]
    public class City
    {
        [XmlElement(ElementName = "string", Namespace = "http://tempuri.org/")]
        public List<string> String { get; set; }
    }

    [XmlRoot(ElementName = "ServiceAreas", Namespace = "http://tempuri.org/")]
    public class ServiceAreas
    {
        [XmlElement(ElementName = "City", Namespace = "http://tempuri.org/")]
        public City City { get; set; }
    }

    [XmlRoot(ElementName = "ArrayOfServiceAreas", Namespace = "http://tempuri.org/")]
    public class ArrayOfServiceAreas
    {
        [XmlElement(ElementName = "ServiceAreas", Namespace = "http://tempuri.org/")]
        public ServiceAreas ServiceAreas { get; set; }
        [XmlAttribute(AttributeName = "xsd", Namespace = "http://www.w3.org/2000/xmlns/")]
        public string Xsd { get; set; }
        [XmlAttribute(AttributeName = "xsi", Namespace = "http://www.w3.org/2000/xmlns/")]
        public string Xsi { get; set; }
        [XmlAttribute(AttributeName = "xmlns")]
        public string Xmlns { get; set; }
    }

我能夠毫無問題地讀取您的XML文件。

這是我使用的序列化器:

 public class Serializer
    {
        public T Deserialize<T>(string input) where T : class
        {
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));

            using (StringReader stringReader = new StringReader(input))
            {
                return (T)xmlSerializer.Deserialize(stringReader);
            }
        }

        public string Serialize<T>(T ObjectToSerialize)
        {
            XmlSerializer xmlSerializer = new XmlSerializer(ObjectToSerialize.GetType());
            StringBuilder builder = new StringBuilder();
            using (StringWriterWithEncoding textWriter = new StringWriterWithEncoding(builder, Encoding.UTF8))
            {
                xmlSerializer.Serialize(textWriter, ObjectToSerialize);
                return textWriter.ToString();
            }
        }
    }
    public class StringWriterWithEncoding : StringWriter
    {
        Encoding encoding;

        public StringWriterWithEncoding(StringBuilder builder, Encoding encoding)
        : base(builder)
        {
            this.encoding = encoding;
        }

        public override Encoding Encoding
        {
            get { return encoding; }
        }
    }

最后是執行:

 var serializer = new Serializer();

//I used a local file for testing, but it should be the same thing with your api response
                var xmlInputData = File.ReadAllText(@"MyXmlPath");

                var output = serializer.Deserialize<ArrayOfServiceAreas>(xmlInputData);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM