使用LINQ插入新的XML节点 [英] Insert new XML node using LINQ

查看:73
本文介绍了使用LINQ插入新的XML节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

XML: 1个 aa 2个 bbb

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文件中插入新的节点问题"

how insert new Node 'Question' to XML File

推荐答案

目前尚不清楚您的问题是什么意思,但是更新XML文件的基本过程如下:

It's unclear exactly what your question means, but the basic process of updating the XML file would be along the lines of:

  • 就像已经将XML文档加载到内存中一样
  • 确定要更改的元素,这取决于条件是什么
  • 更新它(例如,根据您的评论将Value属性设置为"kkk")
  • 使用doc.Save("file.xml")或类似的方法保存XML文档
  • Load the XML document into memory, as you're already doing
  • Identify the element you want to change, which will depend on what the criteria are
  • Update it (e.g. setting the Value property to "kkk" as per your comments)
  • Save the XML document using doc.Save("file.xml") or something similar

如果没有更精确的要求,很难比这更精确.但是,作为示例,如果您想在文档中的每个Text节点前添加"Question x:"前缀,其中x是问题的ID,则可以编写以下内容:

It's hard to be more precise than that without having more precise requirements. As an example though, if you wanted to prefix every Text node in the document with "Question x: " where x is the ID of the question, you might write something like:

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":

Or to change every "aaa" Text element to "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");

这篇关于使用LINQ插入新的XML节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆