Как обновить старый элемент новым в C # / XML - PullRequest
0 голосов
/ 12 октября 2019

В основном я хочу сделать следующее: скачать новый XML-файл и заменить некоторые элементы старым, например, заменить этот код:

<Run x:Name="Degree" Text="15"/>

на текущую степень, равную

<temperature value="280.15" min="278.15" max="281.15" unit="kelvin"/>

но я не знаю, как это сделать. Вот мой код, с которым я застрял:

using (WebClient web = new WebClient())
{
    string url = string.Format("https://samples.openweathermap.org/data/2.5/weather?q=London&mode=xml&appid=b6907d289e10d714a6e88b30761fae22");
    var xml = web.DownloadString(url);
}

1 Ответ

0 голосов
/ 12 октября 2019

Использовать 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 URL = "https://samples.openweathermap.org/data/2.5/weather?q=London&mode=xml&appid=b6907d289e10d714a6e88b30761fae22";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(URL);

            XElement temperature = doc.Descendants("temperature").FirstOrDefault();
            temperature.SetAttributeValue("value", 281);

            string oldXml = "<Root xmlns:x=\"abc\"><Run x:Name=\"Degree\" Text=\"15\"/></Root>";

            XDocument oldDoc = XDocument.Parse(oldXml);
            XElement run = oldDoc.Descendants("Run").FirstOrDefault();

            run.ReplaceWith(temperature);

        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...