使用Xpath C#无法从FQL获取内部文本

时间:2012-07-27 16:02:31

标签: c# xml facebook xpath facebook-fql

我正在尝试从名为sharecount的XML标记中获取内部文本,我需要通过normalized_url标记来获取它,如下所示:

    string ShareCount;
    string Url = "'" + "http://www.example.com/Article.aspx?id=" + GuideID + "'";
    XmlNode Node;
    try
    {
        //return Share count (using Xpath). 
        XmlDoc.SelectSingleNode("fql_query_response/link_stat[normalized_url=" + Url + "]/share_count");
        ShareCount = XmlDoc.InnerText;
        int.TryParse(ShareCount, out Value); //Turn string to int.
        return Value;
    }
    catch
    {
        return 0;
    }

这是XML:

<fql_query_response xmlns="http://api.facebook.com/1.0/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" list="true">
<link_stat>
<url>http://www.example.com/Article.aspx?id=1909</url>
<normalized_url>http://www.example.com/Article.aspx?id=1909</normalized_url>
<share_count>11</share_count>
<like_count>3</like_count>
<comment_count>0</comment_count>
<total_count>14</total_count>
<commentsbox_count>8</commentsbox_count>
<comments_fbid>10150846665210566</comments_fbid>
<click_count>0</click_count>
</link_stat>
</fql_query_response>
<link_stat>
<url>http://www.example.com/Article.aspx?id=1989</url>
<normalized_url>http://www.example.com/Article.aspx?id=1989</normalized_url>
<share_count>11</share_count>
<like_count>3</like_count>
<comment_count>0</comment_count>
<total_count>14</total_count>
<commentsbox_count>8</commentsbox_count>
<comments_fbid>10150846665210566</comments_fbid>
<click_count>0</click_count>
</link_stat>
</fql_query_response>

事情是我得到了返回值:“www.example.com/Article.aspx?id=1132http://www.example.com/Article.aspx?id=190900000101502138970422760”我做错了什么?谢谢!

1 个答案:

答案 0 :(得分:0)

问题是您正在选择单个节点,但从根元素获取内容。最重要的是,您有一个根命名空间,因此需要使用NameSpaceManger进行搜索。试试这个样本:

        string GuideID = "1989";
        string Url = "'" + "http://www.example.com/Article.aspx?id=" + GuideID + "'";

        var XmlDoc = new XmlDocument();

        XmlDoc.Load(new FileStream("XMLFile1.xml",FileMode.Open,FileAccess.Read));
        var nsm = new XmlNamespaceManager(XmlDoc.NameTable);
        nsm.AddNamespace("s", "http://api.facebook.com/1.0/");

        var node = XmlDoc.SelectSingleNode("s:fql_query_response/s:link_stat[s:normalized_url=" + Url + "]/s:share_count", nsm);
        var ShareCount = node.InnerText;            

这是LINQ方式,具有相同的命名空间管理器和XPathSelector。

XDocument xdoc = XDocument.Load(new FileStream("XMLFile1.xml", FileMode.Open, FileAccess.Read));
        var lnode = xdoc.XPathSelectElements("s:fql_query_response/s:link_stat[s:normalized_url=" + Url + "]/s:share_count",nsm).First();
        var ret = lnode.Value;