将xml解析为object,在tag-QT之间打印内容

时间:2017-10-19 07:35:18

标签: c++ xml qt parsing tags

我已经阅读了这个xml:

<item>...</item>
    <item>
        <title>Lamar Alexander, Jeff Sessions, Xi Jinping: Your Wednesday Evening Briefing</title>
        <link>https://www.nytimes.com/2017/10/18/briefing/jeff-sessions-lamar-alexander-xi-jinping.html?partner=rss&amp;emc=rss</link>
        <guid isPermaLink="true">https://www.nytimes.com/2017/10/18/briefing/jeff-sessions-lamar-alexander-xi-jinping.html</guid>
        <atom:link rel="standout" href="https://www.nytimes.com/2017/10/18/briefing/jeff-sessions-lamar-alexander-xi-jinping.html?partner=rss&amp;emc=rss"/>
        <media:content url="https://static01.nyt.com/images/2017/10/18/briefing/18eveningss-slide-3PL9/18eveningss-slide-3PL9-moth.jpg" medium="image" height="151" width="151"/>
        <media:description/>
        <media:credit>J. Scott Applewhite/Associated Press</media:credit>
        <description>Here&#x2019;s what you need to know at the end of the day.</description>
        <dc:creator>KAREN ZRAICK and SANDRA STEVENSON</dc:creator>
        <pubDate>Wed, 18 Oct 2017 23:37:23 GMT</pubDate>
    </item>
<item>...</item>

我正在尝试打印title属性:

QDomNodeList list = doc.elementsByTagName("item");

QDomElement elem = list.at(0); //this containt first item content
qDebug() << elem.attribute("title");

但是qDebug()什么都不打印。为什么?如何获取标签之间的内容?

由于

1 个答案:

答案 0 :(得分:1)

因为标题不是属性,所以它是元素!属性例如 guid 元素中的 isPermaLink ,或 atom中的 href :link

QDomElement elem = list.at(0).toElement();
QDomElement title = elem.firstChildElement("title");
if(!title.isNull())qDebug() << title.text();
QDomElement guid = elem.firstChildElement("atom:link");
if(!guid.isNull())qDebug() << guid.attribute("href");