给出这个xml文件
<root>
<event id="123">
<option subID="1">English</option>
<option subID="2">German</option>
<option subID="3">French</option>
<option subID="4">Spanish</option>
</event>
</root>
如何将西班牙语的值更改为日语?
我有这个linq查询:
var nodeToEdit = xml.Descendants("event").Where(x => (string)x.Attribute("subID") == "4");
并且在使用此查询执行某些操作后,我使用此更改值:
foreach(var item in nodeToEdit.Elements())
{
var query = item.Descendants("option").Where(z => (string)z.Attribute("subID").Value == "4");
foreach (var bla in query)
{
bla.Value = "Japanese"; // bla.Value = Spanish
}
}
但是当我调试时,我发现我的query
没有结果。
答案 0 :(得分:0)
如果这是您的实际代码和XML,那么它不会因多个原因而起作用。这是解决它的一种可能方法:
//select <event> node by id attribute
var nodeToEdit = xml.Descendants("event")
.FirstOrDefault(x => (string)x.Attribute("id") == "123");
if(nodeToEdit != null)
{
//select <option> node within current <event> by subID attribute
var optionToEdit = nodeToEdit.Elements()
.FirstOrDefault(z => (string)z.Attribute("subID") == "4");
optionToEdit.Value = "Japanese";
}
或者,只有以下情况仍然被认为是可读的,您可以一次性完成:
//select <option> node based on id attribute of it's parent & subID attribute of it's own
var nodeToEdit = xml.Descendants("option")
.FirstOrDefault(x => (string)x.Parent.Attribute("id") == "123"
&&
(string)x.Attribute("subID") == "4"
);