[英]How do I select a specific xmlnode and change it values
My xml looks like this.... 我的xml看起来像这样...
<?xml version="1.0" encoding="utf-8"?>
<messwerte>
<messwert>
<tag>1</tag>
<niederschlag>46</niederschlag>
<temperatur>7,6</temperatur>
<druck>4,6</druck>
</messwert>
......
</messwerte>
Now, I wanna give aa specific day where I want to change "niederschlag" "temperatur" and "druck" and I tried this: 现在,我想给一个特定的日子,我想更改“ niederschlag”,“ temperatur”和“ druck”,并尝试了以下操作:
public static void WriteXML(int day, double[] mess, string path)
{
XmlDocument doc = new XmlDocument();
doc.Load(path);
XmlElement nieder = doc.SelectSingleNode("/messwerte/messwert" + Convert.ToString(day) + "/niederschlag") as XmlElement;
if (nieder != null)
{
nieder.InnerText = Convert.ToString(mess[0]);
}
}
And it wont work. 它不会工作。 And I know it's baaaad and super basic but i cant get it to work....... 而且我知道这是baaaad和超级基础的,但是我无法使它工作。
I would suggest the reason it won't work for you, is you're trying to do 2 different things with one xpath string. 我建议它对您不起作用的原因是,您正在尝试使用一个xpath字符串执行2种不同的操作。
First you have to find the messwert
element with a tag
element that has an InnerText value matching the day
value you're passing in. 首先,您必须找到带有tag
元素的messwert
元素,该元素的InnerText值与您要传递的day
值相匹配。
Once you've identified the right element you want to change the InnerText of the niederschlag
element. 确定正确的元素后,您要更改niederschlag
元素的InnerText。
Even though writing this out makes it seem quite complicated, leveraging a LINQ query can simplify it tremendously: 即使将其写成看起来很复杂,利用LINQ查询也可以极大地简化它:
public static void WriteXML(int day, double[] mess, string path)
{
XmlDocument doc = new XmlDocument();
doc.Load(path);
var nieder = (from XmlElement element in doc.GetElementsByTagName("messwert")
where element.SelectSingleNode("tag").InnerText == day.ToString()
select element).First().SelectSingleNode("niederschlag");
if (nieder != null)
{
nieder.InnerText = mess[0].ToString();
}
doc.Save(path);
}
This code assumes your data is strongly controlled and that you'll never be looking for a day that isn't there. 该代码假定您的数据受到严格控制,并且您永远不会寻找没有一天的日子。
If this isn't the case you'll have to assign the query including the First()
method to a temporary variable, and check if it's null. 如果不是这种情况,则必须将包含First()
方法的查询分配给临时变量,并检查其是否为null。
Something like this should work: 这样的事情应该起作用:
public static void WriteXML(int day, double[] mess, string path)
{
XmlDocument doc = new XmlDocument();
doc.Load(path);
var messwert = (from XmlElement element in doc.GetElementsByTagName("messwert")
where element.SelectSingleNode("tag").InnerText == day.ToString()
select element).FirstOrDefault();
if(messwert == null)
{
throw new ArgumentException($"The day value, doesn't exist. the value passed is {day}");
}
var nieder = messwert.SelectSingleNode("niederschlag");
if (nieder != null)
{
nieder.InnerText = mess[0].ToString();
}
doc.Save(path);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.