首页 > 解决方案 > 如何在 C#/XML 中用新元素更新旧元素

问题描述

基本上我想做的是:下载一个新的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);
}

标签: c#.netxmlwpfxaml

解决方案


使用 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);

        }
    }
}

推荐阅读