2016-11-17 133 views
0

我使用遺留系統(而不是我的設計),它將一些數據作爲序列化XML(SOAP)保存在數據庫中。使用XDocument解析SOAP XML

XML是使用SoapFormatter創建的。

SoapFormatter formatter = new SoapFormatter(); 
formatter.Serialize(stream, o); 

由於版本控制問題,我不能簡單地反序列化SOAP。從中創建數據的模型已經發生變化,持久數據的反序列化(在xml中)是不可能的。所以我想弄清楚如何手動將舊SOAP「反序列化」到現有模型。

我可以加載到XDocument,然後用LINQ提取節點值。但是我對Guid值有問題。它們存儲在SOAP XML中,如下所示:

<someId xsi:type="a2:Guid" xmlns:a2="http://schemas.microsoft.com/clr/ns/System"> 
       <_a>1396006029</_a> 
       <_b>2720</_b> 
       <_c>20328</_c> 
       <_d>162</_d> 
       <_e>217</_e> 
       <_f>181</_f> 
       <_g>57</_g> 
       <_h>113</_h> 
       <_i>92</_i> 
       <_j>64</_j> 
       <_k>35</_k> 
      </someId> 

有沒有辦法做到這一點無痛人意?

我可以通過一個類似這樣的閱讀一個:

var someId = xdoc.Descendants(ns + "root").Elements("someId").Elements("_a").Value; 

,並嘗試解析到的Guid,但它並不好看。

感謝,

邁克下面

回答

0
I added <Root xmlns:xsi="abc"> to xml because the xsi namespace wan't defined. 

try代碼:

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

namespace ConsoleApplication28 
{ 
    class Program 
    { 
     const string FILENAME = @"c:\temp\test.xml"; 
     static void Main(string[] args) 
     { 
      Dictionary<string, int> dict = new Dictionary<string, int>(); 
      XDocument doc = XDocument.Load(FILENAME); 
      XElement someId = doc.Descendants("someId").FirstOrDefault(); 

      dict = someId.Elements().GroupBy(x => x.Name.LocalName, y => (int)y) 
       .ToDictionary(x => x.Key, y => y.FirstOrDefault()); 


     } 
    } 
}