C# Foreach 循环 XmlNodeList
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11847965/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Foreach loop XmlNodeList
提问by Devator
Currently I have the following code:
目前我有以下代码:
XmlDocument xDoc = new XmlDocument();
xDoc.Load("http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=twitter");
XmlNodeList tweets = xDoc.GetElementsByTagName("text");
foreach (int i in tweets)
{
if (tweets[i].InnerText.Length > 0)
{
MessageBox.Show(tweets[i].InnerText);
}
}
Which doesn't work, it gives me System.InvalidCastExceptionon the foreach line.
哪个不起作用,它给了我System.InvalidCastExceptionforeach 行。
The following code works perfectly (no foreach, the iis replaced with a zero):
以下代码完美运行(没有 foreach,i用零替换):
XmlDocument xDoc = new XmlDocument();
xDoc.Load("http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=twitter");
XmlNodeList tweets = xDoc.GetElementsByTagName("text");
if (tweets[0].InnerText.Length > 0)
{
MessageBox.Show(tweets[0].InnerText);
}
采纳答案by eburgos
tweets is a node list. I think that what you're trying to do is this:
tweets 是一个节点列表。我认为你想要做的是:
XmlDocument xDoc = new XmlDocument();
xDoc.Load("http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=twitter");
XmlNodeList tweets = xDoc.GetElementsByTagName("text");
for (int i = 0; i < tweets.Count; i++)
{
if (tweets[i].InnerText.Length > 0)
{
MessageBox.Show(tweets[i].InnerText);
}
}
回答by Shyju
It is not of Inttype, That is the reason you are getting a casting exception. You can either replace int with the appropriate type or simply make use of type inference (implicitly typed variables)to handle this. Here i am using typeinference.by saying type as var, The compiler will understand it is of type of the iterator variable in tweetscollection
它不是Int类型,这就是您收到强制转换异常的原因。您可以用适当的类型替换 int 或简单地使用类型推断(隐式类型变量)来处理这个问题。这里我使用typeinference.by 说 type as var,编译器会理解它是tweets集合中迭代器变量的类型
foreach (var i in tweets)
{
if (i!=null)
{
string tweet= (((System.Xml.XmlElement)(i))).InnerText;
MessageBox.Show(tweet);
}
}
EDIT :With the Wonderful LINQtoXML, Your code can be rewritten like this.
编辑:使用 Wonderful LINQtoXML,您的代码可以像这样重写。
string url = "http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=twitter";
XElement elm = XElement.Load(url);
if (elm != null)
{
foreach (var status in elm.Elements("status"))
{
string tweet = status.Element("text").Value;
MessageBox.Show(ss);
}
}
回答by YAYAYAYA
I know that there is already a marked answer, but you can do it like you did in your first try, you just need to replace the int with XmlNode
我知道已经有一个标记的答案,但是您可以像在第一次尝试时那样做,您只需要将 int 替换为 XmlNode
XmlDocument xDoc = new XmlDocument();
xDoc.Load("http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=twitter");
XmlNodeList tweets = xDoc.GetElementsByTagName("text");
foreach (XmlNode i in tweets)
{
if (i.InnerText.Length > 0)
{
MessageBox.Show(i.InnerText);
}
}
回答by HMR
All the answers seem to be a bit outdated Imperativeexamples so I will add a declarative one. This is not doing what the OP wanted but I'm sure you'll get the point.
所有的答案似乎都有点过时的命令式示例,因此我将添加一个声明式示例。这不是在做 OP 想要的,但我相信你会明白这一点。
public static List<System.Xml.XmlNode> toList(System.Xml.XmlNodeList nodelist){
List<System.Xml.XmlNode> nodes = new List<System.Xml.XmlNode>();
foreach (System.Xml.XmlNode node in nodelist)
{
nodes.Add(node);
}
return nodes;
}
public static ReadMeObject setXml(ReadMeObject readmeObject){
readmeObject.xmlDocument = new System.Xml.XmlDocument();
readmeObject.xmlDocument.LoadXml("<body>"+readmeObject.htmlStringContent+"</body>");
System.Xml.XmlNodeList images = readmeObject.xmlDocument.SelectNodes("//img");
Array.ForEach(
Functions.toList( images )
.Where((image) => image.Attributes != null)
.Where((image) => image.Attributes["src"] != null)
.Where((image) => image.Attributes["src"].Value != "")
.ToArray()
, (image) => {
Console.WriteLine(image.Attributes["src"].Value);
}
);
return readmeObject;
}
回答by Joseph
foreach (XmlNode node in tweets)
{
if (tweets[i].InnerText.Length > 0)
{
MessageBox.Show(tweets[node].InnerText);
}
}
I've changed the 'I', which you cannot use, to XmlNode, which selects a single line of your list.
我已将您无法使用的“I”更改为 XmlNode,它会选择您的列表中的一行。
回答by Jean-Pascal Lavigne
You can loop through the Collection with .GetEnumerator()
您可以使用 .GetEnumerator()
this code is taken Microsoft Documentation :
此代码采用 Microsoft 文档:
XmlNodeList elemList = root.GetElementsByTagName("title");
IEnumerator ienum = elemList.GetEnumerator();
while (ienum.MoveNext()) {
XmlNode title = (XmlNode) ienum.Current;
Console.WriteLine(title.InnerText);
}
回答by Kevin Hayes Anderson
Use this simple extension method to iterate through XmlNodeList:
使用这个简单的扩展方法来遍历 XmlNodeList:
public static void ForEachXml<TXmlNode>(this XmlNodeList nodeList, Action<TXmlNode> action)
{
foreach (TXmlNode node in nodeList) action(node);
}
Method Call:
方法调用:
xDoc.GetElementsByTagName("text").ForEachXML<XmlNode>(tweet =>
{
if (tweet.InnerText.Length > 0)
MessageBox.Show(tweet.InnerText);
});

