XmlNodelist中的XmlNode [英] XmlNode in XmlNodelist

查看:363
本文介绍了XmlNodelist中的XmlNode的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道错误在哪里吗?还是将视频名称转换为字符串的更好方法?

Does anyone know where is mistake? Or is better way to get video name into string?

string text = "<?xml version='1.0' encoding='UTF-8'?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:media='http://search.yahoo.com/mrss/' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:gd='http://schemas.google.com/g/2005' xmlns:yt='http://gdata.youtube.com/schemas/2007'><entry><title>VIDEO NAME</title></entry></feed>";
string xpath = "feed/entry";
XmlDocument xml = new XmlDocument();
xml.LoadXml(text);
XmlNodeList nodes = xml.SelectNodes(xpath);
foreach (XmlNode node in nodes)
{
    string title = node["title"].InnerText;
    MessageBox.Show(title);
}

XML

<?xml version='1.0' encoding='UTF-8'?>
    <feed xmlns='http://www.w3.org/2005/Atom' xmlns:media='http://search.yahoo.com/mrss/' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:gd='http://schemas.google.com/g/2005' xmlns:yt='http://gdata.youtube.com/schemas/2007'>
      <entry>
        <title>VIDEO NAME</title>
      </entry>
    </feed>

推荐答案

在Xml xmlns='http://www.w3.org/2005/Atom'中的此声明将文档中所有没有名称空间前缀的元素放在默认名称空间http://www.w3.org/2005/Atom/中.因此,您需要在XPath查询中使用名称空间:

This declaration in the Xml xmlns='http://www.w3.org/2005/Atom' puts all elements in the document that don't have a namespace prefix in the default namespace http://www.w3.org/2005/Atom/. Therefore you need to use namespaces in your XPath queries:

        string text = "<?xml version='1.0' encoding='UTF-8'?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:media='http://search.yahoo.com/mrss/' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:gd='http://schemas.google.com/g/2005' xmlns:yt='http://gdata.youtube.com/schemas/2007'><entry><title>VIDEO NAME</title></entry></feed>";

        XmlDocument xml = new XmlDocument();
        xml.LoadXml(text);
        XmlNamespaceManager nsmgr = new System.Xml.XmlNamespaceManager(xml.NameTable);
        nsmgr.AddNamespace("atom", "http://www.w3.org/2005/Atom");
        string xpath = "atom:feed/atom:entry/atom:title";
        XmlNodeList nodes = xml.SelectNodes(xpath, nsmgr);

        foreach (XmlNode node in nodes)
        {
            Console.WriteLine(node.InnerText);
        }

这篇关于XmlNodelist中的XmlNode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆