2013-11-21 49 views
0

我需要一個好的庫來處理XML - 比較/差異.NET。 我需要一個圖書館,讓我比較的XML文件,然後得到的結果作爲一個XML文件,只包含的區別: 例如:如何找到一個好的庫來處理C#中的XML

XML1:

<標籤=「gentype」值=的 「Java」/>

XML2: <標籤= 「gentype」 值= 「C#」/>

然後,結果應該是這樣的: <標籤= 「gentype」 值= 「C#」 status =「changed」 />

+3

_Questions要求我們建議或找到一個工具,庫或喜愛的異地資源是題外話堆棧Overflow_ –

+0

是在buitin的XmlReader不夠的,你想做什麼? – liquidsnake786

+1

'System.Xml.Linq'? –

回答

1

我建議將2 xml文件反序列化爲2個對象,並比較這2個對象以找出差異。 例如:

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

namespace ConsoleApplication5 { 
    class Program { 
     static void Main(string[] args) { 
      var xml1 = "<?xml version=\"1.0\" encoding=\"utf-8\" ?> <entity tag=\"gentype\" value=\"java\" />"; 
      var xml2 = "<?xml version=\"1.0\" encoding=\"utf-8\" ?> <entity tag=\"gentype\" value=\"c#\" />"; 

      var entity1 = DeserializeFrom(xml1); 
      var entity2 = DeserializeFrom(xml2); 

      if (entity1 != entity2) { 
       entity1.Status = "changed"; 
      } 

      var newxml = SerializeTo(entity1); 
      Console.WriteLine(newxml); 
      Console.Read(); 
     } 

     static Entity DeserializeFrom(String xmlText) { 
      var bytes = Encoding.UTF8.GetBytes(xmlText); 
      using (var stream = new MemoryStream(bytes)) { 
       var serializer = new XmlSerializer(typeof(Entity)); 
       return (Entity)serializer.Deserialize(stream); 
      } 
     } 

     static String SerializeTo(Entity entity) { 
      var bytes = new byte[1024]; 
      using (var stream = new MemoryStream(bytes)) { 
       var serializer = new XmlSerializer(typeof(Entity)); 
       serializer.Serialize(stream, entity); 
      } 
      return Encoding.UTF8.GetString(bytes); 
     } 


    } 

    [XmlRoot("entity")] 
    public class Entity { 
     [XmlAttribute("tag")] 
     public String Tag { get; set; } 

     [XmlAttribute("value")] 
     public String Value { get; set; } 

     [XmlAttribute("status")] 
     public String Status { get; set; } 

     public override bool Equals(object obj) { 
      var entity = (Entity)obj; 
      return this.Tag == entity.Tag && this.Value == entity.Value; 
     } 
    } 
} 
+0

請問你能更精確些嗎? –

+0

請參閱上面的我更新的答案。 – yyou

相關問題