2012-07-16 59 views

回答

1

Linq2Xml可以使生活更輕鬆。

XDocument xDoc = XDocument.Load("http://api.serviceu.com/rest/events/occurrences?orgkey=613dc2ce-0b32-4926-8e7e-33ee279be1cb"); 
var list = xDoc.Descendants("Occurrence") 
      .Select(o => new Item 
      { 
       Category = (string)o.Element("CategoryList"), 
       EMail = (string)o.Element("ContactEmail"), 
       Description = (string)o.Element("Description"), 
      }) 
      .ToList(); 


public class Item 
{ 
    public string Category; 
    public string EMail; 
    public string Description; 
} 
+0

在這些元素上調用'.Value'可能會有好處。 – 2012-07-16 18:32:28

+0

@MarkusJarderot謝謝,我更新了答案 – 2012-07-16 18:41:57

+0

Lb ..如何將它分配給列表而不是數組?類似oChLifeItems.Category = o.Element(「CategoryList」) – Tronics 2012-07-16 18:46:26

0
XmlTextReader reader = new XmlTextReader(strURL); 

    while (reader.Read()) 
    { 
     switch(reader.Name) 
     { 
      case "ContactEmail": 
        //reader.ReadElementContentAsString(); 
       break; 
      //... 
     } 
    } 

我會爲XML文檔中的每個集合創建一個支持類。

+0

背襯類創建具有相同名稱和類型的XML屬性的類。 – 2012-07-16 18:45:03

+0

嗨尼克,當使用上面的代碼時我收到錯誤,當我嘗試聯繫電子郵件...錯誤是這樣的。ReadElementContentAsString方法不支持節點類型EndElement。行1,位置100 – Tronics 2012-07-16 19:33:32

+0

的代碼是這樣的一段時間(reader.Read()){ 開關 (reader.Name) { 案 「所屬分類」: VAR貓= reader.ReadElementContentAsString(); 休息; case「ContactEmail」: var email = reader.ReadElementContentAsString(); 休息; } } – Tronics 2012-07-16 19:33:53

2

您可以使用XmlReader

using(XmlReader reader = XmlReader.Create("...")) 
{ 
    while (reader.Read()) 
    { 
     if (reader.IsStartElement()) 
     { 
      switch (reader.Name) 
      { 
       case "CategoryList": 
        var cat = reader.ReadElementContentAsString(); 
        break; 
       case "ContactEmail": 
        var email = reader.ReadElementContentAsString(); 
        break; 
      } 
     } 
    } 
} 

XmlDocument絲毫XPath

XmlDocument document = new XmlDocument(); 
document.Load("..."); 
foreach (XmlNode node in document.SelectNodes("//CategoryList")) 
{ 
    var cat = node.InnerText; 
} 

foreach (XmlNode node in document.SelectNodes("//ContactEmail")) 
{ 
    var email = node.InnerText; 
} 

或LINQ到XML作爲L.B提及。

0
[DataContract(Name = "Occurrence", Namespace = "")] 
class Occurrence 
{ 
    [DataMember] 
    public string CategoryList { get; set; } 
    [DataMember] 
    public string ContactEmail { get; set; } 
    [DataMember] 
    public string Description { get; set; } 
} 
var ser = new DataContractSerializer(typeof(List<Occurrence>), "Occurrences", ""); 

List<Occurrence> objects = null; 
using (var reader = XmlReader.Create(strURL)) 
{ 
    objects = (List<Occurrence>) ser.ReadObject(reader); 
} 
相關問題