C# 如何根据子元素和父元素的属性更改子元素的值?
给定这个xml文件C# 如何根据子元素和父元素的属性更改子元素的值?,c#,xml,linq,C#,Xml,Linq,给定这个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&g
<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>
在对这个查询进行了一些操作之后,我使用这个来更改值:
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
}
}
但是当我调试时,我可以看到我的
查询没有结果。如果这是您的实际代码和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";
}
//按id属性选择节点
var nodeToEdit=xml.substands(“事件”)
.FirstOrDefault(x=>(字符串)x.Attribute(“id”)==“123”);
if(nodeToEdit!=null)
{
//在“当前按子ID”属性中选择节点
var optionEdit=nodeToEdit.Elements()
.FirstOrDefault(z=>(字符串)z.Attribute(“子ID”)==“4”);
optionEdit.Value=“日语”;
}
或者,只有在您仍然认为以下内容可读的情况下,您可以一次性完成:
//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"
);
//根据其父节点的id属性选择节点,并根据其自身的subID属性选择节点
var nodeToEdit=xml.substands(“选项”)
.FirstOrDefault(x=>(字符串)x.Parent.Attribute(“id”)==“123”
&&
(字符串)x.Attribute(“子ID”)=“4”
);
您确定您的XML不使用名称空间吗?
没有subID
属性:var nodeToEdit=XML.substands(“事件”)。其中(x=>(string)x.attribute(“subID”)==“4”)代码>
//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"
);