在 C# 中修改单个 XML 属性 [英] Modify a single XML attribute in C#
本文介绍了在 C# 中修改单个 XML 属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经很好地编写了 XML 文档,它看起来像这样
I've got it writing the XML doc fine, and it will look something like this
<Team>
<Character Name="Bob" Class="Mage"/>
<Character Name="Mike" Class="Knight"/>
</Team>
我试图找到一种方法来访问单个字符的类"属性并对其进行修改.到目前为止,我已经到了可以精确定位特定字符的地步,但我不知道如何访问 'Class' 属性并为字符修改它.
I'm trying to find a way to access "Class" attribute of a single character and modify it. So far, i've got it to the point where I can pinpoint a specific character, but I can't figure out how to access the 'Class' attribute and modify it for the char.
void Write(string path, string charName, string varToChange, string value){
XmlNode curNode = null;
XmlDocument doc = new XmlDocument();
doc.Load(path);
XmlElement rootDoc = doc.DocumentElement;
curNode = rootDoc;
if(curNode.HasChildNodes){
for(int i=0; i<curNode.ChildNodes.Count; i++){
if(charName == curNode.ChildNodes[i].Attributes.GetNamedItem("Name").Value){
// Code would go here
}
}
}
return;
}
推荐答案
使用 XPATH:
XmlDocument doc = new XmlDocument();
doc.Load(path);
var nodes = doc.SelectNodes(String.Format("/Team/Character[@Name=\"{0}\"]", charName));
foreach (XmlElement n in nodes)
{
n.SetAttribute(varToChange, value);
}
这篇关于在 C# 中修改单个 XML 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文