Unanswered Managing XPaths

  • Tuesday, May 08, 2012 9:22 PM
     
      Has Code

    I deal with a lot of XML data in my job.  One constant requirement is to be able to manage XPath.  I may have an XML Document and need a particular node set in that document, then I might do a XPathSelectElements and need to acces the same node set, but my XPath has changed.  I may need to pass an XML Document from one namespace to another and need a common place to store (and share) the location of particular node sets within an XML Document.

    One option I've tried is to create a static Global class to store my XPaths in.  But, if I have an XML document which I now have to iterate on using XPathSelectElements, then my XPath is no longer correct.

    For example, if my XML document looks like

    <root>
    <sub1>
    <sub2></sub2>
    <sub2></sub2>
    </sub1>
    <sub1></sub1>
    <sub1></sub1>
    <sub1></sub1>
    </root>


    I can set a static Property in a static class "Global" called "xpSub2_a" to the value @"/root/sub1/sub2".  If, instead, I do

    List<XElement> sub1set = xdoc.XPathSelectElements(@"/root/sub1");
    foreach (XElement item in sub1set)
    {
    List<XElement> sub2sets = item.XPathSelectElements(Global.xpSub2_b);
    }

    Global.xpSub2_b would be equal to "sub2".

    So, I end up with something that looks like

    static Global
    {
    public string const xpSub2_b = "sub2";
    public string const xpSub2_a = @"/root/sub1/sub2";
    }

    Is there a cleaner way to manage all of these XPath statements?




    • Edited by Newmanb1 Tuesday, May 08, 2012 9:33 PM
    •  

All Replies

  • Wednesday, May 09, 2012 9:50 AM
     
     

    Currently I don't understand what the problem is. Do you want to store XPath expressions that you can combine, so that one path can be evaluated relative to a result found with another path? For your sample you would need the paths

      "/root/sub1"

    and

      "sub2"

    that way you could nest XPathSelectElements as you do in your C# sample.

    Or you could concatenate the paths e.g.

      XPathSelectElements("/root/sub1" + "/" + "sub2")

    to only use one call.


    MVP Data Platform Development My blog