gpt4 book ai didi

c# - XmlNodelist 中的 XmlNode

转载 作者:行者123 更新时间:2023-12-03 05:46:39 25 4
gpt4 key购买 nike

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

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 查询中使用 namespace :

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

关于c# - XmlNodelist 中的 XmlNode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15311194/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com