2010-08-10 94 views
1

這是我會得到響應:如何解析XML?

<?xml version="1.0" encoding="utf-8"?> 
<rsp stat="ok"> 
     <image_hash>cxmHM</image_hash> 
     <delete_hash>NNy6VNpiAA</delete_hash> 
     <original_image>http://imgur.com/cxmHM.png</original_image> 
     <large_thumbnail>http://imgur.com/cxmHMl.png</large_thumbnail> 
     <small_thumbnail>http://imgur.com/cxmHMl.png</small_thumbnail> 
     <imgur_page>http://imgur.com/cxmHM</imgur_page> 
     <delete_page>http://imgur.com/delete/NNy6VNpiAA</delete_page> 
</rsp> 

我怎麼能提取每個標籤的價值?

XDocument response = new XDocument(w.UploadValues("http://imgur.com/api/upload.xml", values)); 
string originalImage = 'do the extraction here'; 
string imgurPage = 'the same'; 
UploadedImage image = new UploadedImage(); 
+0

請參閱http://stackoverflow.com/questions/55828/best-practices-to-parse-xml-files – 2010-08-10 15:05:54

回答

6

幸運的是這很簡單:

string originalImage = (string) response.Root.Element("original_image"); 
string imgurPage = (string) response.Root.Element("imgur_page"); 
// etc 

這是假設你XDocument構造函數的調用是正確的......不知道什麼w.UploadValues呢,這很難說。

LINQ to XML使查詢變得非常簡單 - 讓我們知道你是否有更復雜的東西。

請注意,我使用了一個強制轉換而不是Value屬性或類似的東西。這意味着如果缺少<original_image>元素,originalImage將爲空,而不是拋出異常。你可能更喜歡這個例外,這取決於你的具體情況。

+0

謝謝,喬恩。我怎樣才能檢索根標籤的'stat'屬性? – 2010-08-10 15:09:01

+0

@Sergio:好的,你可以調用'response.Root.Attribute(「stat」)。Remove()' - 但是如果你只是解析它的數據,爲什麼要麻煩? – 2010-08-10 15:20:33

+0

該統計數據爲我提供了有關上傳是否正確的信息。 :p – 2010-08-10 15:25:43

0

.NET框架內置了一個優秀的,易於使用的XML解析器。請參閱here以供參考。

0

一種方法是使用.net xsd.exe tool爲您在問題中指出的rsp xml塊創建包裝類。一旦創建了類,您可以簡單地使用以下代碼塊將xml searealize到可直接在代碼中使用的對象中。當然,總是有Xpath或linq,就像Jon所說的選項一樣,如果你喜歡像上面那樣將xml加載到和xmldocument對象中。

public static rsm GetRsmObject(string xmlString) 
    { 
     XmlSerializer serializer = new XmlSerializer(typeof(rsm)); 
     rsm result = null; 

     using (XmlTextReader reader = new XmlTextReader(new StringReader(xmlString))) 
     { 
      result = (rsm)serializer.Deserialize(reader); 
     } 

     return result; 
    } 

Enjoy!

+1

它不在XmlDocument中 - 它在XDocument中,這使得這種事情變得很微不足道。就我個人而言,我不會爲此而惹惱XmlSerializer。 – 2010-08-10 15:21:12

+0

我喜歡XmlSerializer,但是我確實看到XDocument和linq使這非常簡單。 – Doug 2010-08-10 15:24:44