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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16012390/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 23:42:34  来源:igfitidea点击:

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

c#.netxmlxpath

提问by mazury

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

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

XPath:

X路径:

/bookstore/author/first-name

C#:

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 Stringelement.

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

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

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

采纳答案by Vyktor

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

谷歌搜索c# .net xpath几秒钟后,您会找到这篇文章,其中提供了可以轻松修改以使用的示例XPathDocumentXPathNavigator以及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.

我建议更多阅读xPath 语法。多得多。

回答by M?rten Wikstr?m

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

回答by vijay

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

您也可以使用 Linq to XML 来获取指定元素的值

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.

从上面的查询中,您将获得 ParaLine 标记内的所有字符串元素的值。