这是我的xml:
<settings>
<Element Name="a" Attribute="b" />
<Element Name="b" Attribute="c" />
</settings>
这是我的代码:
const string SettingsFileName = "settings.xml";
XmlDocument xmlDocument = new XmlDocument();
const string RootNode = "settings";
const string elementName = "Element";
const string attributeName = "Name";
const string attributeValue = "b";
xmlDocument.Load(SettingsFileName);
XElement xElement = XElement.Load(new XmlNodeReader(xmlDocument));
var entry = from element in xElement.Elements(elementName)
where (string)element.Attribute(attributeName) == attributeValue
select element;
string[] values = { "Attribute", "d" };
xElement = entry.First<XElement>();
for (int i = 0; i < values.Length; i++)
{
string name = values[i++];
string value = "";
if (i < values.Length)
value = values[i];
xElement.Attribute(name).Value=value;
}
我想使用XElement更新xmlDocument,最好不使用XDocument。我似乎错过了一步,因为它没有做到:
xmlDocument.Save(SettingsFileName);
这是可能的,如果是的话,怎么样?
答案 0 :(得分:0)
想出来。这是解决方案:
text2
答案 1 :(得分:0)
我并没有真正关注&#39;为什么&#39;这里。你正在做的事似乎很疯狂。坚持XDocument
:
var doc = XDocument.Load(SettingsFileName);
var attribute = doc
.Descendants("Element")
.Attributes("Attribute")
.Single(x => x.Value == "b");
attribute.Value = "d";
doc.Save(SettingsFileName);