XML: 1 AAA 2 BBB
代码
var doc = XDocument.Load (Server.MapPath(".") + "\\Questions.config");
var elements = from element in doc.Descendants("Question")
select new
{
Id = element.Element("Id").Value,
Text = element.Element("Text").Value,
Reserver = element.Element("Reserver") != null
};
StringBuilder builder = new StringBuilder();
foreach (var question in elements)
{
builder.AppendLine(question.Id + "-" + question.Text);
}
myTextBox.Text = builder.ToString();
如何将新节点“问题”插入XML文件
答案 0 :(得分:1)
你想做这样的事吗?
var doc = XDocument.Load (Server.MapPath(".") + "\\Questions.config");
var elements = from element in doc.Descendants("Question")
select new
{
Id = element.Element("Id").Value,
Text = element.Element("Text").Value,
Reserver = element.Element("Reserver") != null
};
StringBuilder builder = new StringBuilder();
foreach (var question in elements)
{
builder.AppendLine(question.Id + "-" + question.Text);
}
myTextBox.Text = builder.ToString();
编辑:如果您想更新每个问题,那么您必须稍微修改上述代码。
var elements = from element in doc.Descendants("Question")
select new
{
Id = element.Element("Id"),
Text = element.Element("Text"),
Reserver = element.Element("Reserver")
};
StringBuilder builder = new StringBuilder();
foreach (var question in elements)
{
// Read
builder.AppendLine(question.Id.Value + "-" + question.Text.Value);
// Write
question.Reserver.Value = "True";
}
myTextBox.Text = builder.ToString();
通过这种方式,您不再选择值,而是选择XElement,因此您可以修改XML。还要记住使用XDocument.Save()
保存文件。
答案 1 :(得分:1)
目前还不清楚你的问题到底意味着什么,但更新XML文件的基本过程将是:
doc.Save("file.xml")
或类似的如果没有更精确的要求,很难更精确。举个例子,如果你想为文档中的每个Text
节点添加前缀“问题x:”,其中x是问题的ID,你可以写一些类似的东西:
var doc = XDocument.Load("file.xml");
var elements = doc.Descendants("Question");
foreach (var question in elements)
{
int id = (int) question.Element("ID");
XElement textElement = question.Element("Text");
textElement.Value = "Question: " + id + " = " + textElement.Value;
}
doc.Save("changed.xml");
或者将每个“aaa”文本元素更改为“kkk”:
var doc = XDocument.Load("file.xml");
var elements = doc.Descendants("Text")
.Where(x => x.Value == "aaa");
foreach (var textElement in elements)
{
textElement.Value = "kkk";
}
doc.Save("changed.xml");