Accepted answer

XPath is a selection expression language -- it never modifies the XML document(s) it operates on.

Therefore, in order to obtain the desired new XML document, you need to either use XML DOM (not recommended) or apply an XSLT transformation to the XML document. The latter is the recommended way to go, since XSLT is a language especially designed for tree transformations.

In .NET one can use the XslCompiledTransform class and its Transform() method. Read more about these in the relevant MSDN documentation.

The XSLT transformation itself is extremely simple:

<xsl:stylesheet version="1.0"
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:template match="node()|@*">
   <xsl:apply-templates select="node()|@*"/>

 <xsl:template match="dvd[not(location/city='london')]"/>

Here, you can find a complete code example how to obtain the result of the transformation as an XmlDocument (or if desired, as an XDocument).


Here's an example using LINQ to XML.

//load the document
var document = XDocument.Load(@"C:\Development\Website\dvds.xml");
//get all dvd nodes
var dvds = document.Descendants().Where(node => node.Name == "dvd");
//get all dvd nodes that have a city node with a value of "london"
var londonDVDs = dvds.Where(dvd => dvd.Descendants().Any(child => child.Name == "city" && child.Value == "london"));

Related Articles