C#从xml文件中读取某些元素/属性

时间:2015-03-07 13:20:09

标签: c# xml

我试图从以下xml文件(作为控制台程序)中读取某些属性

http://api.openweathermap.org/data/2.5/forecast?q=lahti,fin&mode=xml

正如您在' forecast' 元素中看到的那样,有多个' time' 元素。我想要的是选择某些&time;' 元素,然后在其中选择给定的内容(假设' symbol' )并打印它拥有的所有/任何属性。

我希望能够控制我选择的' 元素和我想要打印的属性。

我所能做的就是打印每个'时间' 元素及其属性,并设法打印给定&#内的每个属性39;时间' 元素。但我无法想象如何控制它。

使用以下代码,我可以在第一个' time' 元素中打印所有内容。 Item(0)是元素的索引,for循环确保我没有空行。从xml文件中可以看出,一些&time;' 元素在其中有不同的属性,所以我想我需要通过索引名称来调用它们。

    static void xmlReader()
    {
        int i;

        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(parseLink());

        foreach (XmlNode xmlNode in xmlDoc.DocumentElement.GetElementsByTagName("time").Item(0))
            for (i = 0; i < xmlNode.Attributes.Count; i++)
            {
                Console.WriteLine(xmlNode.Attributes[i].Value);
            }
        Console.ReadKey();

    }

5 个答案:

答案 0 :(得分:1)

使用Linq2Xml,它更容易和方便。

public static void Main()
{
    var forecast = XDocument.Load(@"http://api.openweathermap.org/data/2.5/forecast?q=lahti,fin&mode=xml")
                            .Root
                            .Element("forecast");

    foreach (var time in forecast.Elements("time")
                                 .Where(e => e.Element("clouds")
                                              .Attribute("value")
                                              .Value == "overcast clouds"))
    {
        Console.WriteLine(time.Element("symbol").Attribute("name").Value);
    }
}

答案 1 :(得分:0)

您可以使用XmlReadertutorial)作为流动资料,

此处,我从from元素和time属性name元素获取sybol属性。它们用于相同的Time元素。还添加了云的值

的提取示例
 using (XmlReader reader = XmlReader.Create(@"http://api.openweathermap.org/data/2.5/forecast?q=lahti,fin&mode=xml"))
 {
      // Walk through all Elements 
      while (reader.Read())
      {
         // If we meet time element ; go inside and walk 
         if (reader.Name == "time")
         {
               Console.WriteLine("A new TIME ");

               // Extract from attribute
               String from = reader["from"];
               if (from != null)
               {
                    Console.WriteLine("\t From : " + from);
               }

               // Now walk through all elements inside same Time element
               // Here I use do-while ; what we check is End element of time : </time> .. when we walk till we meet </time> we are inside children of same Time
               // That mean we start from <time> and walk till we meet </time>
               do
               {
                    reader.Read();

                    if (reader.Name == "symbol")
                    {
                         // You can use this approach for any Attribute in symbol Element
                         String name = reader["name"];
                         if (name != null)
                         {
                              Console.WriteLine("\t Symbol name :" + name);
                         }
                    }

                    if (reader.Name == "clouds")
                    {
                         String clouds = reader["value"];
                         if (clouds != null)
                         {
                           Console.WriteLine("\t\t Clouds value : " + clouds);
                         }
                     }

              } while (reader.NodeType != XmlNodeType.EndElement && reader.Name != "time");

          }
      }
}

只需在您的控制台程序中尝试此操作..

答案 2 :(得分:0)

类似@ aush的回复,但有一些格式

        var doc = XDocument.Load(@"http://api.openweathermap.org/data/2.5/forecast?q=lahti,fin&mode=xml");
        var forecastEl = doc.Root.Element(XName.Get("forecast"));

        var timeNodes = from e in forecastEl.Elements("time")
                       where e.Element("symbol")
                            .Attribute(XName.Get("name"))
                            .Value == "light snow"
                       select e;

        var colFormat = "{0,-20} {1,-20} {2,-30}";
        Console.WriteLine(colFormat, "TimeFrom", "TimeTo", "SymbolName");
        foreach(var time in timeNodes)
            Console.WriteLine(colFormat
                , time.Attribute("from").Value
                , time.Attribute("to").Value
                , time.Element("symbol").Attribute("name").Value);

结果:

TimeFrom             TimeTo               SymbolName 
2015-03-07T12:00:00  2015-03-07T15:00:00  light snow 
2015-03-07T15:00:00  2015-03-07T18:00:00  light snow

答案 3 :(得分:0)

在这里使用XDocument有点容易......

private static void XmlOutput()
    {
        var filePathAndName = @"http://api.openweathermap.org/data/2.5/forecast?q=lahti,fin&mode=xml";
        var xmlDoc = XDocument.Load(filePathAndName);

        // Get list of Nodes matching the "time" name or any other filters you wish.
        var nodes = xmlDoc.Descendants().Where(nd => nd.Name.LocalName == "time");

        // Filter the node list to only those where the date is as specified (and any other filters you wish).
        // This could be done in the initial linq query - just making it clearer here.
        nodes = nodes.Where(nd => nd.Attributes().Any(cnd => cnd.Name.LocalName == "from" && cnd.Value.Contains("2015-03-07")));

        foreach (XElement element in nodes)
        {
            // For each descendant node where named "symbol"... 
            foreach(var node in element.Descendants().Where(nd => nd.Name.LocalName == "symbol"))
            {
                // Write out these particular attributes ("number" and "name")
                string output = "";
                output += node.Attributes().FirstOrDefault(nd => nd.Name.LocalName == "number").Value;
                output += ", " + node.Attributes().FirstOrDefault(nd => nd.Name.LocalName == "name").Value;
                Console.WriteLine(output);
            }
        }

        Console.ReadKey();
    }

答案 4 :(得分:0)

使用我的xml library here,您可以搜索实际的DateTime值,如下所示:

XElement root = XElement.Load(@"http://api.openweathermap.org/data/2.5/forecast?q=lahti,fin&mode=xml");

var search = DateTime.Parse("2015-03-07T21:00:00");

XElement time = root.XPathElement("//time[@from >= {0} and @to > {1}]", search, search);

var value = time.ToString();

enter image description here