c# - 如何在 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);
}
解决方案
使用 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);
}
}
}
推荐阅读
- php - 如何重新创建套接字文件?
- powershell - 在 PowerShell 中使用 YQ 时出现引用问题
- python - 如何使 pandas 的 read_excel 参数“nrows”动态化
- javascript - MongoError: Topology is closed, please connect - 使用 Jest 运行单元测试时
- python - 当源代码没有改变,但是 selenium webdriver deos 没有返回元素时
- javascript - 基于 2 个数组创建对象数组
- python - PYTHON - 错误:device_event_log_impl.cc(214)] [17:43:52.278] USB:usb_device_handle_win.cc:1056 无法从节点连接读取描述符
- python - Flask 忽略的离线引导程序
- flutter - 为什么我会出现堆栈溢出?
- javascript - 为什么 forEach 适用于 nodeList 但不适用于集合