[英]How to change value of child element based on attribute of child and parent?
給定這個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
沒有結果。
如果那是您的實際代碼和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"
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.