我如何从XML标签获得数据

本文关键字:数据 标签 XML | 更新日期: 2023-09-27 17:51:17

此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.错误

我如何从XML标签获得数据

您的命名空间错误。使用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);
}

本例中的输出为:

印度