2013-04-05 4 views
-1

У меня есть вопрос), как я могу получить значение из определенного узла (информация/погода/день/day_part типа = «День»/Tempreture)Получить значение из узла

<?xml version="1.0" encoding="UTF-8"?> 
<info lang="ru" xmlns:x="http://www.yandex.ru/xscript"> 
    +<region id="213" lon="37.617671" lat="55.755768" zoom="10"/> 
    <traffic lon="37.617671" lat="55.755768" zoom="10" region="213"></traffic> 
    <weather region="213" climate="1"> 
    <source xmlns:xi="http://www.w3.org/2001/XInclude">mb3d</source> 
    <day xmlns:xi="http://www.w3.org/2001/XInclude"> 
     <title>Москва</title> 
     <country>Россия</country> 
     <time_zone>Europe/Moscow</time_zone> 
     <summer-time>0</summer-time> 
     <sun_rise>06:51</sun_rise> 
     <sunset>20:14</sunset> 
     <daytime>d</daytime>+<date date="2013-04-05T00:00:00Z"/> 
     <day_part type="день" typeid="2"> 
     <weather_type>облачно</weather_type> 
     <weather_code>overcast</weather_code> 
     <image>http://weather.yandex.ru/i/5.png</image> 
     <image-v2 size="22x22">http://yandex.st/weather/v-1/i/icons/22x22/ovc_+6.png</image-v2> 
     <image-v3 size="48x48">http://yandex.st/weather/v-1/i/icons/48x48/ovc.png</image-v3> 
     <image_number>5</image_number> 
     <wind_speed>5.0</wind_speed> 
     <wind_direction id="se">юв</wind_direction> 
     <dampness>70</dampness> 
     <pressure>743</pressure> 
     <temperature color="F2F0E6" class_name="t6">+5</temperature> 
     <time_zone>Europe/Moscow</time_zone> 
     <observation_time>17:30</observation_time> 
     <observation>2013-04-05T17:30:00</observation> 
     </day_part> 
     <day_part type="вечер" typeid="3"></day_part> 
     <day_part type="ночь" typeid="4"></day_part> 
     <day_part type="утро" typeid="1"></day_part> 
     <day_part type="день" typeid="2"></day_part> 
     <night_short></night_short> 
     <tomorrow></tomorrow> 
    </day> 
    <url xmlns:xi="http://www.w3.org/2001/XInclude">http://pogoda.yandex.ru/moscow/</url> 
    </weather> 
</info> 

У меня есть код, но как может Уточняю, что мне нужно узел с типом = «день»

XElement elem = xDocument.Element("info"); 
    if (elem != null) 
     foreach (var el in elem.Elements("weather").Elements("day").Elements("day_part")) 
      { 
      var level = el.Element("temperature").Value; 
      listBox1.Items.Add(level); 
      }; 

Этот блок кода возвращает два значения (+5, +6), но мне нужно только один (+5) и бросить исключение.

+0

Прежде всего, ваш XML является недействительным! – MarcinJuraszek

+0

XDocument не загружает такой XML – sll

+0

, это просто часть моего xml. Исходный файл действителен. – user2110490

ответ

0

Прежде всего - ваш входной XML не является действительным, и он не может быть загружен в XDocument. Я установил, что это будет:

<?xml version="1.0" encoding="UTF-8"?> 
<info lang="ru" xmlns:x="http://www.yandex.ru/xscript">+<region id="213" lon="37.617671" lat="55.755768" zoom="10" /> 
<traffic lon="37.617671" lat="55.755768" zoom="10" region="213"></traffic> 
<weather region="213" climate="1"> 
<source xmlns:xi="http://www.w3.org/2001/XInclude">mb3d</source> 
<day xmlns:xi="http://www.w3.org/2001/XInclude"> 
    <title>Москва</title> 
    <country>Россия</country> 
    <time_zone>Europe/Moscow</time_zone> 
    <summer-time>0</summer-time> 
    <sun_rise>06:51</sun_rise> 
    <sunset>20:14</sunset> 
    <daytime>d</daytime> 
    <date date="2013-04-05T00:00:00Z"></date> 
    <day_part type="день" typeid="2"> 
      <weather_type>облачно</weather_type> 
      <weather_code>overcast</weather_code> 
      <image>http://weather.yandex.ru/i/5.png</image> 
      <image-v2 size="22x22">http://yandex.st/weather/v-1/i/icons/22x22/ovc_+6.png</image-v2> 
      <image-v3 size="48x48">http://yandex.st/weather/v-1/i/icons/48x48/ovc.png</image-v3> 
      <image_number>5</image_number> 
      <wind_speed>5.0</wind_speed> 
      <wind_direction id="se">юв</wind_direction> 
      <dampness>70</dampness> 
      <pressure>743</pressure> 
      <temperature color="F2F0E6" class_name="t6">+5</temperature> 
      <time_zone>Europe/Moscow</time_zone> 
      <observation_time>17:30</observation_time> 
      <observation>2013-04-05T17:30:00</observation> 
    </day_part> 
    <day_part type="вечер" typeid="3"></day_part> 
    <day_part type="ночь" typeid="4"></day_part> 
    <day_part type="утро" typeid="1"></day_part> 
    <day_part type="день" typeid="2"></day_part> 
    <night_short></night_short> 
    <tomorrow></tomorrow> 
</day> 
<url xmlns:xi="http://www.w3.org/2001/XInclude">http://pogoda.yandex.ru/moscow/</url> 
</weather> 
</info> 

С такого входа вы можете получить желаемые узлы значения с помощью метода XPathSelectElements расширения:

var results = xDocument.XPathSelectElements("info/weather/day/day_part[@type='день']/temperature") 
         .Select(e => (string)e) 
         .ToList(); 

Для документа XML, показанный выше results содержит одну string значения: +5.

Однако, я хотел бы предложить поиск day_part элемента, используя typeid значение атрибута вместо type:

var results = xDocument.XPathSelectElements("info/weather/day/day_part[@typeid=2]/temperature") 
         .Select(e => (string)e) 
         .ToList(); 

Тех же результатов, но меньше шансов потерпеть неудачу из-за кодирование.

Вы можете заполнить ваш ListBox:

foreach (var value in results)) 
{ 
    listBox1.Items.Add(value); 
}; 
+0

Не работает (result.count = 0 – user2110490

+0

Итак, ваш входной XML должен быть структурирован иначе, чем образец. – MarcinJuraszek

+0

http://export.yandex.ru/bar/reginfo.xml? region = 213 здесь is original xml – user2110490

0

Try что-то вроде этого

if (elem != null) 
      elem.Descendants("day_part").Where(el => el.Attribute("type").Value == "день") 
       .ToList().ForEach(el => listBox1.Items.Add(el.Element("temperature").Value)); 
+0

null Исключение для ссылки :( – user2110490

+0

Если все эти примеры дают вам исключения для нулевой ссылки, может быть что-то еще неправильно. У всех элементов day_part есть атрибут типа и элемент температуры? –

+0

Я не заметил, что xml изменился из-за у меня было исключение ссылочной ссылки – user2110490

0

Вы можете использовать расширение XPath для XLinq:

using System.Xml.Linq; 
using System.Xml.XPath; 
... 
var doc = XDocument.Load("test.xml"); 
IEnumerable<XElement> dayElements = doc.XPathSelectElements("/info/weather/day/day_part[@type=\"день\"]"); 
Смежные вопросы