此XML文件是使用Wikipedia API?
获得的<SearchSuggestion version="2.0" xmlns="http://opensearch.org/searchsuggest2">
<Query xml:space="preserve">India</Query>
<Section>
<Item>
<Image source="http://upload.wikimedia.org/wikipedia/en/thumb/4/41/Flag_of_India.svg/50px-Flag_of_India.svg.png" width="50" height="33" />
<Text xml:space="preserve">India</Text>
<Description xml:space="preserve">India (), officially the Republic of India ('), is a country in South Asia. It is the seventh-largest country by area, the second-most populous country with over 1.2 billion people, and the most populous democracy in the world. </Description>
<Url xml:space="preserve">http://en.wikipedia.org/wiki/India</Url>
</Item>
</Section>
</SearchSuggestion>
我试过这个:
var texts = doc.Descendants("Text");
foreach (var text in texts)
{
Debug.WriteLine(text.Value);
}
但是我遇到了Object reference not set to an instance of an object.
错误。然后我尝试了这个:
XNamespace aw = "https://www.google.org";
IEnumerable<XElement> de = from el in doc.Descendants(aw + "Text")
select el;
foreach (XElement el in de)
Console.WriteLine(el.Name);
但是这段代码给了我一个System.NullReferenceException;Object reference not set to an instance of an object.
错误。
答案 0 :(得分:0)
您的命名空间错误。使用LINQ2XML,您可以使用默认文档命名空间,然后按照标记名称Text
提取节点:
var xml = XDocument.Parse(xmlSource); // or XDocument.Load("c:\path\input.xml");
var ns = xml.Root.GetDefaultNamespace();
var textNodes = xml.Root.Descendants(ns + "Text").ToList();
foreach (var textNode in textNodes)
{
Console.WriteLine(textNode.Value);
}
这种情况下的输出是:
印度