8

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#?

0

3 Answers 3

28

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I've had to deal with XPathNavigator, XPathDocument... . Problem is that file doesnt look like a simple xml. I mean <NameElement1><NameElement2>abababababababa</NameElement2></NameElement1>. One element include another element, here: <NameElement1<NameElement2 <NameElement3 abababababababa>>>. So simple XPath syntax doesn't work "/Cell/CellContent/Para/ParaLine/String/text()";. I ask about sth other solution then simple xpath expresion.
@mazury than it's not valid XML and you cannot use xPath
4

You can use Linq to XML as well to get value of specified element

var list = XDocument.Parse("xml string").Descendants("ParaLine")
                 .Select(x => x.Element("string").Value).ToList();

From above query you will get value of all the string element which are inside ParaLine tag.

Comments

3
navigator.SelectSingleNode("/Cell/CellContent/Para/ParaLine/String/text()").Value

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.