根据名称在XML中查找属性

问题描述 投票:0回答:1

我对使用XML文档很陌生。以前,我已经根据位置提取了所需的值(“ wCData”是加载的XML文档的变量):

```string nowImageCode = wCData.ChildNodes.Item(1).ChildNodes.Item(8).Attributes.Item(2).Value;```

但是,我认为位置可能已经改变,因此我需要一种基于名称而不是位置将值分配给字符串的方法。这是一个删除城市的示例,用于获得一定数量的安全性:

<current>
<city id="6666666" name="Timbuktu">
<coord lon="-79.34" lat="37.31"/>
<country>US</country>
<timezone>-18000</timezone>
<sun rise="2019-12-23T12:28:39" set="2019-12-23T22:03:57"/>
</city>
<temperature value="43.43" min="37.99" max="46.99" unit="fahrenheit"/>
<feels_like value="37.06" unit="fahrenheit"/>
<humidity value="61" unit="%"/>
<pressure value="1022" unit="hPa"/>
<wind>
<speed value="4.7" unit="mph" name="Light breeze"/>
<gusts/>
<direction value="40" code="NE" name="NorthEast"/>
</wind>
<clouds value="1" name="clear sky"/>
<visibility value="16093"/>
<precipitation mode="no"/>
<weather number="800" value="clear sky" icon="01d"/>
<lastupdate value="2019-12-23T15:01:55"/>
</current>

我需要拉的值是图标,在这种情况下是“ 01d”。

xml openweathermap
1个回答
0
投票

使用xml linq:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            string icon = (string)doc.Descendants("weather").FirstOrDefault().Attribute("icon");
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.