[英]How to change an attribute in a subnode in C#?
I want to change the attribute value (in this case "51") of the "NextMemberId" in an xml file that looks like this: 我想在xml文件中更改“NextMemberId”的属性值(在本例中为“51”),如下所示:
<File>
<MemberList>
<NextMemberId Value="51" />
<Member Id="1" ..... />
<Member Id="2" ..... />
</MemberList>
</File>
The following code works, but I would like to know if it can be done in a more direct way without having to run a foreach loop: 以下代码有效,但我想知道是否可以以更直接的方式完成而无需运行foreach循环:
var memberId = 1;
var memberlist = Doc.DocumentElement.SelectSingleNode("MemberList");
foreach (XmlNode node in memberlist.ChildNodes)
{
var nodeElement = node as XmlElement;
if (nodeElement != null && nodeElement.Name == "NextMemberId")
{
nodeElement.SetAttribute("Value", memberId.ToString());
}
}
Thanks for any inspiration! 感谢您的灵感!
The correct path to get NextMemberId
from File
according to your sample XML would be : 根据您的示例XML从
File
获取NextMemberId
的正确路径是:
var nodeElement = Doc.DocumentElement.SelectSingleNode("MemberList/NextMemberId");
nodeElement.SetAttribute("Value", memberId.ToString());
If there are multiple NextMemberId
in your actual XML, and you need to filter by Value
attribute, then you can add an XPath predicate similar to what the other answer suggested : 如果您的实际XML中有多个
NextMemberId
,并且您需要按Value
属性进行过滤,那么您可以添加类似于其他答案建议的XPath谓词:
var nodeElement = Doc.DocumentElement.SelectSingleNode("MemberList/NextMemberId[@Value=51");
Notice that you can choose to keep or leave single-quotes around 51
depending on whether you want compare the Value
as a string or a number , respectively. 请注意,您可以选择在
51
左右保留或保留单引号,具体取决于您是要将Value
分别比较为字符串还是数字 。
您可以选择具有指定属性的单个节点,如下所示:
var nextMemberIdNode = Doc.DocumentElement.SelectSingleNode("NextMemberId[@Value='51']")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.