如何从XML获取此值?

时间:2011-10-28 09:03:52

标签: c# xml

我有这个XML:

<meteo_italia>
    <localita>
        <id>2861</id>
        <nome>Foppolo</nome>
        <prov>BG</prov>
        <capoluogo>0</capoluogo>
        <regione>LOMBARDIA</regione>
        <previsione time="2011-10-28T06:00">
            <id_tempo>6</id_tempo>
            <desc_tempo>temporali isolati</desc_tempo>
            <temp>2</temp>
            <press>1024.3</press>
            <um_rel>78</um_rel>
            <zerot>3000 m</zerot>
            <qn>ND</qn>
            <v_dir>ESE</v_dir>
            <v_int>4 nodi</v_int>
            <ore_s>3</ore_s>
            <prec>0-10mm</prec>
        </previsione>
        <previsione time="2011-10-28T12:00">
            <id_tempo>6</id_tempo>
            <desc_tempo>temporali isolati</desc_tempo>
            <temp>11</temp>
            <press>1024.9</press>
            <um_rel>46</um_rel>
            <zerot>3550 m</zerot>
            <qn>ND</qn>
            <v_dir>SSO</v_dir>
            <v_int>3 nodi</v_int>
            <ore_s>3</ore_s>
            <prec>0-10mm</prec>
        </previsione>

        ... XML continues...

我想从C#上的第二个节点temp中提取值previsione

试过:

using (var wc = new WebClient())
{
    m_strFilePath = wc.DownloadString(xmlMeteo);
}

XmlDocument myXmlDocument = new XmlDocument();
myXmlDocument.LoadXml(m_strFilePath);

try
{
    Response.Write("Value : " + myXmlDocument.SelectSingleNode("//previsione[position()=0]//temp").Value);
}
catch { }   

但我无法得到它。

3 个答案:

答案 0 :(得分:3)

尝试将您的查询更改为:

"//previsione[2]/temp"

并访问.InnerText而不是.Valuesince .Value rarely has an actual value,永远不会访问元素。)

[2]应该(根据要求)获取第二个项目; /temp表示“名为temp的子元素”。

答案 1 :(得分:1)

看起来你的XPath字符串是错误的 - 在你得到它的地方使用双斜杠(“//”)是为了得到一个后代(http://www.tizag.com/xmlTutorial/xpathdescendant.php)。

尝试使用一个斜杠,因为它只会让孩子。

//previsione[2]/temp

此外 - XSLT元素不是从零开始的,因此元素从pos = 1

开始

这是一个我发现非常适合获取xPath字符串的网站它也可以很好地格式化XML! !

http://xmltoolbox.appspot.com/index.html

答案 2 :(得分:1)

XPath的节点位置基于1,而不是0.请尝试:

myXmlDocument.SelectSingleNode("//previsione[2]/temp/text()").Value;