2011-11-01 62 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