代码之家  ›  专栏  ›  技术社区  ›  Sergio Tapia

如何解析XML?

  •  1
  • Sergio Tapia  · 技术社区  · 14 年前

    这就是我将得到的回应:

    <?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();
    
    3 回复  |  直到 14 年前
        1
  •  6
  •   Jon Skeet    14 年前

    幸运的是,这很简单:

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

    假设你的 XDocument 构造函数调用正确…不知道什么 w.UploadValues 是的,很难说。

    LINQtoXML使查询变得非常简单-如果有更复杂的内容,请告诉我们。

    注意,我使用了一个强制转换字符串,而不是 Value 财产或类似的东西。这意味着如果 <original_image> 缺少元素, originalImage 将为空,而不是引发异常。你 可以 根据具体情况,更喜欢例外情况。

        2
  •  0
  •   Russ    14 年前

    .NET框架有一个内置的优秀、简单易用的XML解析器。见 here 供参考。

        3
  •  0
  •   Doug    14 年前

    一种方法是使用.NET xsd.exe tool 为rsp xml块创建一个包装类。一旦创建了类,您就可以简单地使用下面的代码块将XML密封到一个对象中,您可以直接在代码中使用它。当然总有 Xpath 或者,如果您喜欢像上面所做的那样将XML加载到和xmldocument对象中,那么也可以使用jon所说的linq作为选项。

        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;
        }
    

    享受!