Alex Rivera | Logout

Linq to XML - update/alter the nodes of an XML Document

Asked 2008-12-01T17:13:41.603
21

I've got 2 Questions:

1. I've sarted working around with Linq to XML and i'm wondering if it is possible to change an XML document via Linq. I mean, is there someting like

XDocument xmlDoc = XDocument.Load("sample.xml");

update item in xmlDoc.Descendants("item")
where (int)item .Attribute("id") == id
...

2. I already know how to create and add a new XMLElement by simply using

xmlDoc.Element("items").Add(new XElement(......);

but how can I remove a single entry?

XML sample data:

<items>
  <item id="1" name="sample1" info="sample1 info" web="" />
  <item id="2" name="sample2" info="sample2 info" web="" />
</itmes>
Edit
Report

1 Answer

0

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Linq; //using System.Xml;

namespace XMLtoLinqApp { class Program { static void Main(string[] args) {

        //XmlDocument doc = new XmlDocument();
        //XmlElement newBook=doc.CreateElement("BookParticipant");
        //newBook.SetAttribute("Author");

        //Using Functional Construction to Create an XML Schema
        XElement xBookParticipant = new XElement("BookParticipant",
                                        new XElement("FirstName", "Joe"),
                                        new XElement("LastName", "Rattz"));
        Console.WriteLine(xBookParticipant.ToString());


        //Creates the Same XML Tree as Listing 6-1 but with Far Less Code
        XElement xBookParticipants = new XElement("BookParticipants",
                                        new XElement("BookParticipant",
                                        new XAttribute("type", "Author"),
                                        new XElement("FirstName", "Joe"),
                                        new XElement("LastName", "Rattz")),
                                        new XElement("BookParticipant",
                                        new XAttribute("type", "Editor"),
                                        new XElement("FirstName", "Ewan"),
                                        new XElement("LastName", "Buckingham")));
        Console.WriteLine(xBookParticipants.ToString());


        //-- Disadvatages of XML document
        //System.Xml.XmlElement xmlBookParticipant = new System.Xml.XmlElement("BookParticipant");
        XElement xeBookParticipant = new XElement("BookParticipant");


        XDocument xDocument = new XDocument(new XElement("BookParticipants",
                                            new XElement("BookParticipant",
                                            new XAttribute("type", "Author"),
  
answered 2011-02-02T17:48:40.877

Your Answer