Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get element content using only XPath and C# .NET

Tags:

c#

.net

xml

xpath

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>

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

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

like image 648
mazury Avatar asked Apr 15 '13 09:04

mazury


1 Answers

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

I recommend more reading on xPath syntax. Much more.

like image 51
Vyktor Avatar answered Oct 19 '22 23:10

Vyktor