Answered XPath Expression

  • Friday, March 15, 2013 5:58 AM
     
     

    Hi,

    Before asking my query, i just wanted to explain what the issue am facing:

    I have the XML file with the parent node something like

    <abc:ConnectionProperty>

            <cde:datapath>some value</cde:datapath>

    </abc:ConnectionProperty>

    I have written a Xpath exp to get the value of <cde:datapath> i.e., xpath="//abc:ConnectionProperty/cde:datapath"

    I have written this in C#, am not facing any issues with C# code. The error am getting is for XPath expression i have written i.e., "the expression should evaluate to a node"

    And i think it is because of Colon that is in the node.

    Can anyone explain how to write the XPath expression to get the result as "Some Value".

    Thanks,

    Amit

All Replies

  • Friday, March 15, 2013 12:10 PM
     
     

    You need to define the two namespace-prefixes. An example:

    <?xml version="1.0" encoding="utf-16"?>
    <abc:ConnectionProperty xmlns:abc="http1" xmlns:cde="http2">
      <cde:datapath>some value</cde:datapath>
    </abc:ConnectionProperty>

    If the XML appeared something like the above, you could use LINQ to XML:

          XDocument doc = XDocument.Load(new StringReader(xml));
          string cdeNS = "http2";
          string path = doc.Descendants().Where(p => (p.Name == "{" + cdeNS + "}datapath")).First().Value;

    Morten la Cour

  • Friday, March 15, 2013 12:12 PM
     
     Answered Has Code

    Show us enough details to allow us to easily reproduce the issue. When I execute the code

                XmlDocument doc = new XmlDocument();
                doc.Load("XMLFile1.xml");
    
                XmlNamespaceManager mgr = new XmlNamespaceManager(doc.NameTable);
                mgr.AddNamespace("abc", "http://example.com/abc");
                mgr.AddNamespace("cde", "http://example.com/cde");
    
                XmlNode path = doc.SelectSingleNode("//abc:ConnectionProperty/cde:datapath", mgr);
    
                if (path != null)
                {
                    Console.WriteLine(path.InnerText);
                }

    with the XML being

    <abc:ConnectionProperty xmlns:abc="http://example.com/abc" xmlns:cde="http://example.com/cde">
    
      <cde:datapath>some value</cde:datapath>
    
    </abc:ConnectionProperty>

    I get the result "some value".

    So we need to see the details of your code and not a description telling us you get a certain error without showing details of the code causing the error.


    MVP Data Platform Development My blog

    • Marked As Answer by Amit C A Monday, March 25, 2013 1:00 PM
    •