2017-08-27 35 views
-1

我有以下字符串,表示XML層次:反序列化字符串轉換爲XML時,子元素名稱是動態的

"<cookie page=\"1\"> 
    <pz_requestid last=\"{987A23F4-8582-E711-8114-005056B74623}\" first=\"{9F2E4A8C-EB7D-E711-8116-005056B71CCD}\" /> 
</cookie>"; 

,我需要將其反序列化到一個類。

我的問題是,子元素可以有不同的名稱。例如,在上面的例子中,它的名字是「pz_requestid」,但它可以是別的東西,比如「pz_accountid」。我不知道的是如何構建類層次結構,以便能夠正確地對其進行序列化。

目前,我已經創建了下面的類,只有當元素名稱是pz_requestid作品:

[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)] 
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)] 
public partial class cookie 
{ 
    public entityidfieldid pz_requestid { get; set; } 

    [System.Xml.Serialization.XmlAttributeAttribute()] 
    public int page { get; set; } 
} 

/// <remarks/> 
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)] 
public partial class entityidfieldid 
{ 
    [System.Xml.Serialization.XmlAttributeAttribute()] 
    public string last {get; set;} 

    [System.Xml.Serialization.XmlAttributeAttribute()] 
    public string first { get; set; } 
} 

和反序列化下面的代碼工作:

string inputString = "<cookie page=\"1\"><pz_requestid last=\"{987A23F4-8582-E711-8114-005056B74623}\" first=\"{9F2E4A8C-EB7D-E711-8116-005056B71CCD}\" /></cookie>"; 
XmlSerializer serializer = new XmlSerializer(typeof(cookie)); 
MemoryStream memStream = new MemoryStream(Encoding.UTF8.GetBytes(inputString)); 
cookie mycookie = (cookie)serializer.Deserialize(memStream); 

我需要做什麼來改變以得到我需要的東西?

回答

0

與XML LINQ很簡單

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Xml; 
using System.Xml.Linq; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      string xml = 
       "<cookie page=\"1\">" + 
       "<pz_requestid last=\"{987A23F4-8582-E711-8114-005056B74623}\" first=\"{9F2E4A8C-EB7D-E711-8116-005056B71CCD}\" />" + 
       "</cookie>"; 

      XDocument doc = XDocument.Parse(xml); 

      Entityidfieldid entityidfieldid = doc.Descendants("cookie").Elements().Select(x => new Entityidfieldid() { 
       name = x.Name.LocalName, 
       last = (string)x.Attribute("last"), 
       first = (string)x.Attribute("first") 
      }).FirstOrDefault(); 
     } 
    } 
    public partial class Entityidfieldid 
    { 
     public string name { get; set; } 
     public string last { get; set; } 
     public string first { get; set; } 
    } 
} 
相關問題