Xpath或运算符。如何使用

时间:2011-11-01 15:54:17

标签: xpath operators

我没有准确地知道如何在Xpath中使用或运算符。

假设我有一个xml的结构:

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

我可以使用单个Xpath获得节点B或C的所有A节点。 我知道我可以单独寻找B和看到的结果,并在结果去除重复之后(如下所示),但我确信有更好的方法。

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

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

2 个答案:

答案 0 :(得分:5)

/root/a[b or c]会为您提供<a><b>个孩子的所有<c>元素。

答案 1 :(得分: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