简体   繁体   中英

Insert new XML node using LINQ

XML:

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

How can insert new Question using LINQ like this:

<Question>
      <Id>3</Id>
      <Text>ccc</Text>
      <Reserver />
 </Question>
XDocument doc = XDocument.Parse("<Questions>...</Questions>");
doc.Root.Add(
    new XElement("Question",
        new XElement("Id", 3),
        new XElement("Text", "ccc"),
        new XElement("Reserver"))
    );

You can create a new element like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM