如何仅使用XPath和C#.NET获取元素内容

问题描述:

我找到了很多有关如何通过使用简单的XPath表达式和C#获取节点内容的文章,例如:

I've found a lot of articles about how to get node content by using simple XPath expression and C#, for example:

XPath:

/bookstore/author/first-name

C#:

string xpathExpression = "/bookstore/author/first-name";

nodes = navigator.Select(xpathExpression);

我想知道如何获取元素内的内容,而同一元素位于另一个元素内,另一个元素内.
只需看下面的代码:

I wonder how to get content that is inside of an element, and the same element is inside another element and another and another.
Just take a look on below code:

<Cell>          
    <CellContent>
        <Para>                               
            <ParaLine>                      
                <String>ABCabcABC abcABC abc ABCABCABC.</string> 
            </ParaLine>                      
        </Para>     
    </CellContent>
</Cell>

我只想从 String 元素中提取内容 ABCabcABC abcABC abc ABCABCABC..

I only want to extract content ABCabcABC abcABC abc ABCABCABC. from String element.

您知道如何使用 XPath表达式 .Net C#解决问题吗?

Do you know how to resolve problem by use XPath expression and .Net C#?

搜索 c#.net xpath 几秒钟,您会发现 XPathDocument XPathNavigator :: SelectSingleNode() :

After googling c# .net xpath for few seconds you'll find this article, which provides example which you can easily modify to use XPathDocument, XPathNavigator and XPathNavigator::SelectSingleNode():

XPathNavigator nav;
XPathDocument docNav;
string xPath;

docNav = new XPathDocument("c:\\books.xml");
nav = docNav.CreateNavigator();
xPath = "/Cell/CellContent/Para/ParaLine/String/text()";

string value = nav.SelectSingleNode(xPath).Value

我建议您进一步阅读 xPath语法.还有更多.

I recommend more reading on xPath syntax. Much more.