2010-08-10 78 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