【问题标题】:Insert new XML node using LINQ使用 LINQ 插入新的 XML 节点
【发布时间】:2011-03-13 15:01:30
【问题描述】:

XML:

<Questions>
   <Question>
      <Id>1</Id>
      <Text>aaa</Text>
      <Reserver />
   </Question>
   <Question>
      <Id>2</Id>
      <Text>bbb</Text>
      <Reserver />
 </Question>
</Questions>

如何像这样使用 LINQ 插入新问题:

<Question>
      <Id>3</Id>
      <Text>ccc</Text>
      <Reserver />
 </Question>

【问题讨论】:

    标签: c# .net xml linq linq-to-xml


    【解决方案1】:
    XDocument doc = XDocument.Parse("<Questions>...</Questions>");
    doc.Root.Add(
        new XElement("Question",
            new XElement("Id", 3),
            new XElement("Text", "ccc"),
            new XElement("Reserver"))
        );
    

    【讨论】:

      【解决方案2】:

      你可以像这样创建一个新元素:

      var newElem = new XElement("Question",
          new XElement("Id", 3),
          ...
      );
      xdoc.Root.Add(newElem);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多