Community discussion forum

SelectSingleNode in C# (XPath like in XSLT?)

  • 4 years ago

    I'm wondering how we can use XPath with SelectSingleNode:


    root.SelectSingleNode('/rootelement/author/title/book')


    that doesnt seem to work like XSLT does, what am I doing wrong here?


    thanks.

  • 4 years ago
    This should point you in the right direction:

    Code:

    using System;
    using System.Xml;

    namespace Project1
    {
       class Class
       {
         [STAThread]
         static void Main(string[] args)
         {

         XmlDocument xmlDoc;
         XmlNode     xmlNode;
         String      xpathExpr;

         xmlDoc = new XmlDocument();
         xmlDoc.LoadXml( "<?xml version='1.0'?><root><person><name>Martin Fowler</name></person><person><name>Kent Beck</name></person><person><name>Dave Astels</name></person></root>" );

         xpathExpr = "/root/person[name='Martin Fowler']";
         xmlNode = xmlDoc.SelectSingleNode(xpathExpr);

         Console.WriteLine(xmlNode.OuterXml);
         Console.ReadLine()
       }
     }
    }


    HTH
  • 2 years ago

    Using the above example, how would you get the nodevalue for <name> (i.e I want to return "Martin Fowler")

    XmlNode xmlNode = xmlDoc.SelectSingleNode("root/person/name");

    gives me null for xmlNode.
     

  • 1 year ago

    string sName = xmlDoc.SelectSingleNode(xpathExpr).Attributes["name"].Values;

  • 1 year ago

    Do you know what the syntax would look like if you wanted to find a single node where the name was 'Martin Fowler' as above ... and age = 21. (i.e. two pieces of data used for filtering criteria)?

    Thanks  

  • 1 year ago

    Like this:

            static void Main(string[] args)
            {    
                 XmlDocument xmlDoc;
                 XmlNode     xmlNode;
                 String      xpathExpr;

                 xmlDoc = new XmlDocument();
                 xmlDoc.LoadXml("<?xml version='1.0'?><root><person age='21'><name>Martin Fowler</name></person><person age='51'><name>Martin Fowler</name></person><person><name>Kent Beck</name></person><person><name>Dave Astels</name></person></root>");

                 Console.WriteLine(xmlDoc.OuterXml);
                 Console.WriteLine();

                 xpathExpr = "/root/person[@age='51' and name='Martin Fowler']";
                 xmlNode = xmlDoc.SelectSingleNode(xpathExpr);

                 Console.WriteLine(xmlNode.OuterXml);
                 Console.ReadLine();
            }

     HTH

     

Post a reply

Enter your message below

Sign in or Join us (it's free).

We'd love to hear what you think! Submit ideas or give us feedback