2011-11-01 35 views
2

我没有得到如何在Xpath中使用or运算符。Xpath或运算符。如何使用

假设我有THI结构的XML:

<root> 
    <a> 
     <b/> 
     <c/> 
    </a> 
    <a> 
     <b/> 
    </a> 
    <a> 
     <d/> 
     <b/> 
    </a> 
    <a> 
     <d/> 
     <c/> 
    </a> 
</root> 

可我得到一个XPath的所有节点至极必须尽快节点B或C. 我知道我可以去找B和看到在一个单独的方式和总结后的结果删除重复(如下所示),但我相信有一个更好的办法。

List1 = Xpath(./a/b/..) 
List2 = Xpath(./a/c/..) 
MyResult = (List1 + List2 - Repetitions) 

我想这个解决方案也适用于AND运算符。

回答

5

/root/a[b or c]将为您提供所有<a>元素,其中包含<b><c>子元素。

0

尝试:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Xml; 
using System.Xml.XPath; 
using System.IO; 

namespace XpathOp 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      const string xml = @"<?xml version='1.0' encoding='ISO-8859-1'?> 
       <root> 
        <a> 
         <b/> 
         <c/> 
        </a> 
        <a> 
         <b/> 
        </a> 
        <a> 
         <d/> 
         <b/> 
        </a> 
        <a> 
         <d/> 
         <c/> 
        </a> 
       </root>"; 

      XmlDocument doc = new XmlDocument(); 
      doc.LoadXml(xml); 

      foreach (XmlNode node in doc.SelectNodes("//a[b or c]")) 
      { 
       Console.WriteLine("Founde node, name: {0}, hash: {1}", node.Name, node.GetHashCode()); 
      } 

      XPathDocument xpathDoc = new XPathDocument(new MemoryStream(Encoding.UTF8.GetBytes(xml))); 

      XPathNavigator navi = xpathDoc.CreateNavigator(); 
      XPathNodeIterator nodeIter = navi.Select("//a[b or c]"); 

      foreach (XPathNavigator node in nodeIter) 
      { 
       IXmlLineInfo lineInfo = node as IXmlLineInfo; 
       Console.WriteLine("Found at line {0}, position {1}", lineInfo.LineNumber, lineInfo.LinePosition); 
      } 
     } 
    } 
} 

输出:

Found node, name: a, hash: 62476613 
Found node, name: a, hash: 11404313 
Found node, name: a, hash: 64923656 
Found node, name: a, hash: 44624228 
Found at line 3, position 26 
Found at line 7, position 26 
Found at line 10, position 26 
Found at line 14, position 26