2011-11-01 3 views
2

Xpath 내에서 또는 연산자를 사용하는 방법을 정확히 알지 못했습니다.Xpath 또는 연산자. 사용 방법

의 내가 생 구조의 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] 당신이 중 하나 <b> 또는 <c> 자녀가있는 모든 <a> 요소를 제공 할 것입니다.

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