Sergio Tapia
Sergio Tapia

Reputation: 41138

How to parse XML?

This is the response I'll be getting:

<?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>

How can I extract the value of each tag?

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();

Upvotes: 1

Views: 389

Answers (3)

Doug
Doug

Reputation: 5318

One way is the use the .net xsd.exe tool to create a wrapper class for the rsp xml block you have stated in your question. Once you have the class created you can simply use the following code block to searealize the xml into an object you can use directly in your code. Of course there is always Xpath, or linq as Jon stated as options as well if you prefer to load the xml into and xmldocument object as you have done above.

    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!

Upvotes: 0

Russ
Russ

Reputation: 133

The .NET framework has an excellent, simple to use XML Parser built right in. See here for reference.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500525

Fortunately it's pretty simple:

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

That's assuming your XDocument constructor call is correct... without knowing what w.UploadValues does, that's hard to say.

LINQ to XML makes querying very easy - let us know if you have anything more complicated.

Note that I've used a cast to string instead of taking the Value property or anything like that. That means if the <original_image> element is missing, originalImage will be null rather than an exception being thrown. You may prefer the exception, depending on your exact situation.

Upvotes: 6

Related Questions