【问题标题】:How do I update an Old element with a new one in C#/XML如何在 C#/XML 中用新元素更新旧元素
【发布时间】:2019-10-12 10:46:25
【问题描述】:

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

【问题讨论】:

  • 您需要将数据绑定到您的 WPF 窗口。首先将 xml 转换为某种对象形式,然后将该对象作为 DataContext 绑定到您的窗口。有更简单的方法,在代码隐藏中使用控件名称并将值绑定到 Run 或 TextBlock 元素。
  • x:Name 暗示原始“代码”是 XAML。但是您说您想用 XML 替换它。 确切地,您希望它如何工作?遵循正常的 MVVM 实践并让您的数据(XML)与视图(XAML)完全隔离不是更好吗?充其量,你的问题太宽泛了,坦率地说,你甚至不清楚你在问什么。

标签: c# .net xml wpf xaml


【解决方案1】:

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

        }
    }
}

【讨论】:

  • 如何将代码中的&lt;Run x:Name="Degree" Text="15"/&gt; 值设置为temperature 1?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-19
  • 1970-01-01
相关资源
最近更新 更多