查找xml文件的特定标记的行号

时间:2016-02-19 11:34:35

标签: c# .net xml xml-parsing

如何查找xml文件的特定标签的标签和行号, 例如:

<sec id="fm.s2">
<title>Acknowledgments</title>
</sec>
<p>Center for Evidence and Practice Improvement</p>
<p>Agency for Healthcare Research and Quality</p>
<sec id="fm.s2">
<title>Director</title>
</sec>
<p>Center for Evidence and Practice Improvement</p>
<p>Agency for Healthcare Research and Quality</p>
<sec id="fm.s2">
<title>Acknowledgments</title>
</sec>

在这个例子中,我想获得<title>包含“Acknowledgements”文本的行号。

1 个答案:

答案 0 :(得分:1)

你可以用linq

来做
var xml = XDocument.Load(@"path", LoadOptions.SetLineInfo);

var lineNumbers = xml.Descendants()
            .Where(x =>!x.Descendants().Any() && //exact node contains the value
                        x.Value.Contains("Acknowledgments"))
            .Cast<IXmlLineInfo>()
            .Select(x => x.LineNumber);