【问题标题】:Finding an attribute in XML based on name根据名称在 XML 中查找属性
【发布时间】:2020-04-14 21:05:06
【问题描述】:

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

sstring 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】:

    使用 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().Where(x => x.Name.LocalName == "weather").FirstOrDefault().Attribute("icon");
            }
        }
    }
    

    【讨论】:

    • xml 来自一个 URL。这就是我将它带入并存储它的方式。 ` WebClient wc = new WebClient(); wString = wc.DownloadString(currWeatherURL); wCData.LoadXml(wString);`我尝试实现你的代码,把“wCData”而不是“doc”和“后代”没有定义。我也有你所有的“使用”语句。
    • 必须有命名空间。我修改了代码来处理命名空间。
    猜你喜欢
    • 1970-01-01
    • 2016-12-28
    • 2017-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-15
    相关资源
    最近更新 更多