Hello everyone, tell me, I have an XML file of such content

<Пользователь>Дмитрий</Пользователь> <Пол>Мужчина</Пол> <Дата> <Год>1997</Год> <Месяц>6</Месяц> <День>20</День> <Деятельность>Книги</Деятельность> </Дата> <Пользователь>Анна</Пользователь> <Пол>Женщина</Пол> <Дата> <Год>1993</Год> <Месяц>6</Месяц> <День>20</День> <Деятельность>Путешествия</Деятельность> </Дата> 

I need to count the month and day, and drive them into a variable, but not just any date, but only, for example, where the month int month = read the date;

 if(DateTime.Now.Month == month) { MessageBox("УРА ВСЁ РАБОТАЕТ"); } 

I tried this:

 int day = 0; int month = 0; XmlTextReader read = new XmlTextReader("user.xml"); while (read.Read())// но при компиляции тут ошибка { if (read.Name == "<Дата>" && read.GetAttribute("<День>") == "7") { if (month == DateTime.Now.Month && DateTime.Now.Day + 7 == day) Mess.ShowBalloonTip(2000, "Есть новое событие", "Сегодня есть событие", ToolTipIcon.Info); else MessageBox.Show("СЕГОДНЯ НЕТУ CОБЫТИЙ"); } } 

    2 answers 2

    First: the node name of the function is obtained without angle brackets, i.e. You need to write like this:

     read.Name == "Дата" 

    Secondly: it would be more logical to make the file structure like this:

     <Пользователи> <Пользователь Name="Дмитрий"> <Пол>Мужчина</Пол> <Дата> <Год>1997</Год> <Месяц>6</Месяц> <День>20</День> <Деятельность>Книги</Деятельность> </Дата> </Пользователь> ... </Пользователи> 

    Thirdly: you most likely got the error because you have set the declaration node incorrectly, or not at all. It should have the following form:

     <?xml version="1.0" encoding="UTF-8"?> 

    Well, I would also use English words as node names to avoid problems with the encoding.

    • And where is this node to register? - Angus123
    • At the very beginning of the file, in front of all the data - Donil
    • one
      If we talk about the logical data structure in the file, then the <Деятельность> node, in my opinion, you need to remove it from the <Дата> node. - Shad
    • In fact yes. I somehow did not pay attention - Donil

    It is necessary to slightly modify this answer. using System; using System.Linq; using System.Xml; using System.Xml.Linq;

    public class Test {public static void Main () {string month = "5"; XElement source = XElement.Load (@ "source.xml");

      var parsed = (from date in source.Descendants("Дата") where date.Element("Месяц").Value == month let d = new { Day = date.Element("День").Value, Month = date.Element("Месяц").Value, Year = date.Element("Год").Value } select d) .ToArray(); foreach(var d in parsed) { Console.WriteLine(d); } } 

    }

    • Thanks, but the error remains the same. There are multiple root elements. Line 2, position 2 How to "wrap" everything in <xml> </ xml>? - Angus123
    • So you just need to add the root element. <? xml ...?> <Document> ... </ Document> - stanislav