LA.NET [EN]

May 08

One of the things you might need doing is changing the contents of an existing XML tree. As you might expect, this is possible with the new LINQ To XML API. Lets start with the existing XML tree presented on one of the latests posts. I”m just putting it here again so that you don”t have to open another window if you”re interested in following the rest of the post.

var xml = new XElement( “clients”,
                    new XElement(“client”,
                        new XAttribute(“id”,1),
                        new XElement( “name”, “Luis”),
                        new XElement( “country”, “Portugal”)
                    ),
                    new XElement(“client”,
                        new XAttribute(“id”,2),
                        new XElement( “name”,”John”),
                        new XElement( “country”, “England”)
                    ),new XElement(“client”,
                        new XAttribute(“id”,3),
                        new XElement( “name”, “Paulo”),
                        new XElement( “country”, “Portugal”)
                    )
                );

 

Now, lets see how we can add a new element to the clients XML element. You have several options here, but lets just start with the Add method. Currently, you have two overloads of this method, presented here:

public void Add(object content);
public void Add(params object[] content);

Since we only need to add a new client, we”ll use the first overload:

xml.Add(
                    new XElement(“client”,
                        new XAttribute(“id”, 4),
                        new XElement(“name”, “Jose”),
                        new XElement(“country”, “Spain”)
                        )
                );

After you run the previous code, you should see a new client element added as the last child of the clients XML element. The greatest thing about the Add method is that you can also use it to…add an attribute to the element over which you call the method:

xml.Add( new XAttribute( “company”, “NtComp”) );

This API is really really flexible! So, if you expect to be able to add an attributes and new child element by calling the overloaded method, then you”re absolutely correct. In fact, you can also add another type of nodes with it. For instance, if you want to add a text node, you can simply call the previous method and pass it a XText object initialized with the text you want (though you”ll need to do this in limited scenarios only!).

If you need to insert a node at the beginning of the child collection, you can also call the AddFirst method. This method has 2 overloads which will let you add a node to the beginning of the child nodes collection. Do keep in mind though that this method can only be used to add content. If you try to add an attribute, you”ll get an exception.

The XNode class (which, as you might recall, is the base class of most of the important elements defined by the API) introduces several methods which you can use to add new nodes. The AddAfterSelf and AddBeforeSelf are there to let you add a sibling element. Calling them will only work for nodes, so don”t even try to pass it attributes.

Now that you know how to add, you”ll see that removing is really simple: you only need to call the Remove method. So, if client points to the first client, then you”ll only need to call client.Remove() to detach that element from its parent”s child collection:

var client = xml.Element(“client”);
client.Remove();

Since we”re talking about removing nodes, you should know that there”s also a RemoveAll method, which lets you clear the children elements and attributes from the element over which the method is invoked. The next snippet removes all children nodes and attributes from the xml element:

xml.RemoveAll();

If you”re only interested in “cleaning up” the attributes, there”s also a RemoveAttributes method which you can use just for that. Finally, there”s a RemoveNodes method that you can use to remove one of the several existing nodes from an element. The next snippet removes the text node that is associated with the first client”s name element by using the Remove method:

var name = xml.Element(“client”).Element(“name”).Nodes().First();
name.Remove();

It looks weird, but it does work (btw, I”m using the First extension method introduced by LINQ To Objects to get the first child node of the first client”s name element).

If you”re thinking on removing a text node and then adding a new one to change  the text associated with an existing element, then don”t do it. Seriously! There”s a Value property that will do it for you (check the XElement API).

There”s also a SetElementValue method which you can use to change the value of the first child  element that has the XName you pass to the method. Interestingly, you can also use this method to remove a node. To achieve that, just pass null for the value parameter, like the following snippet shows:

xml.SetElementValue(“client”, null);

I guess that by now we”ve covered almost everything: the only thing left is the replacing nodes with new ones. There are several methods that will let you do this, but I”ll just show you the most used ones. The XElement class introduces 2 important methods: ReplaceAll and ReplaceAttributes. Both are overloaded. Lets see how we can replace the contents of the first client with a new one created on the fly:

var first = xml.Element(“client”);
first.ReplaceAll(
                    new XAttribute(“id”, 4),
             &nbs
p;         new XElement(“name”, “Jose”),
                       new XElement(“country”, “Spain”)
               );

As you”ve already guesses, replacing attributes is done with the ReplaceAttributes method, which follows the same usage of the last example. There”s also a ReplaceNodes, but you won”t be gaining much from this method when compared to the previous one.

Finally, there”s a ReplaceWith method. This method is slightly different from the previous one. Instead of replacing the content, the method will replace the node with the new one that is passed in. That means that the following example will replace the first client with a new one:

var first = xml.Element(“client”);
first.ReplaceWith(
                    new XElement(“client”,
                        new XAttribute(“id”, 4),
                        new XElement(“name”, “Jose”),
                        new XElement(“country”, “Spain”)
                        )
                );

And there you go…you”ve just dropped a XML element and added another that replaced the old one.

And that”s all for today. Even though I”ve covered most of what the API has to offer, I still haven”t show any examples of how you can use LINQ expressions with this API. Stay tunned!

1 comment so far

  1. Malehim
    9:25 am - 12-16-2009

    River Leading,seek fact large ball express clear front studio target touch social effect why send particularly now release fire legislation blue then than drawing element scientist large rural tonight thin citizen decision therefore person channel practice undertake lunch silence merely throughout drive temperature branch road island many people partner phone head adopt study careful essential religion where narrow academic partly program political scheme opportunity my client modern election rare answer available consumer rural those ignore major one estate introduction risk charge well authority basis pocket select tomorrow select recall human

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>