日期:2014-05-18  浏览次数:20853 次

♀XPath的SelectNodes查询有奇怪问题,请高手指教!♂(
在使用SelectNodes查询Xml节点的时候,第一次从根出发没问题,可是从查询出来的节点再次使用SelectNodes就不好使了,如下面的代码,cs的Count最后是0,取不到东西,不知道是什么问题,请指教!

XML文件如下:

<?xml   version= "1.0 "   encoding= "utf-8 "   ?>
<root>
    <subRoot>
        <c> 1 </c>
        <c> 2 </c>
        <c> 3 </c>
        <c> 4 </c>
        <c> 5 </c>
        <c> 6 </c>
    </subRoot>
    <subRoot>
        <c> 7 </c>
    </subRoot>
    <subRoot>
        <c> 8 </c>
    </subRoot>
    <subRoot>
        <c> 9 </c>
    </subRoot>
    <subRoot>
        <c> a </c>
        <c> b </c>
    </subRoot>
    <subRoot>
        <c> c </c>
        <c> d </c>
        <c> e </c>
    </subRoot>
</root>

源程序代码:

XmlDocument   doc   =   new   XmlDocument();
doc.Load(Application.StartupPath   +   @ "\XMLFile1.xml ");
XmlNode   root   =   doc.DocumentElement;
XmlNodeList   subRoots   =   root.SelectNodes( "/root/subRoot ");
foreach   (XmlNode   n   in   subRoots)
{
        XmlNodeList   cs   =   n.SelectNodes( "/subRoot/c ");
}

------解决方案--------------------
foreach (XmlNode n in subRoots)
这里的n已经是subrRoot了,所以你就不能再用n.SelectNodes( "/subRoot/c ");因为你用的是相对路径.

这样写就好啦:
XmlNodeList cs = n.SelectNodes( "c ");

------解决方案--------------------
XmlNodeList cs = n.SelectNodes( "/subRoot/c ");
--》
XmlNodeList cs = n.SelectNodes( "c ");
这样没问题的
我试过了

n这个节点已经是subRoot了
所以如果用n.SelectNodes的时候
Path应该从subRoot的子节点开始