3

In MATLAB, I load an XML file docNode = xmlread('stuff.xml');. stuff.xml is the following:

<?xml version="1.0"?>
<rss version="2.0" xmlns:g="http://somesite.com">
    <channel>
        <title>Blah</title>
        <link>http://www.blah.com</link>
        <description>BLAH.COM </description>
        <item>    
            <link>http://www.blah.com/page</link>
        </item>
    </channel>
</rss>

I'm trying to retrieve that string in <link> but it is proving to be quite tricky.. I'm reading this blog http://blogs.mathworks.com/desktop/2010/11/01/xml-and-matlab-navigating-a-tree/ but I still can't figure it out! Can someone chime in on how to get access to <link>? TIA!

1 Answer 1

3

Does this do what you need?

>> docNode = xmlread('stuff.xml');
>> l = docNode.getElementsByTagName('link');
>> char(l.item(0).getFirstChild.getData)
ans =
http://www.blah.com
>> char(l.item(1).getFirstChild.getData)
ans =
http://www.blah.com/page

PS you have an error in stuff.xml - it should be </channel>, not </<channel>.


Edit: To loop directly through each link, you can use l.getLength:

for i = 0:(l.getLength - 1) % 0-based indexing, not 1-based like MATLAB arrays
    char(l.item(i).getFirstChild.getData)
end

ans =
http://www.blah.com
ans =
http://www.blah.com/page
Sign up to request clarification or add additional context in comments.

2 Comments

Hey Sam, yes it does. Thank you so much! If there are more than one <item>, how do you loop through them?
Discard the question. I figured it out shortly after posting it. I'm wondering why you would get the link element first instead of serially access it, though. But all works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.