find line number of specific tag of xml file [dupl

2019-09-21 14:37发布

问题:

This question already has an answer here:

  • get line number for XElement here 2 answers

How to find tag and line number of Specific tag of xml file, for example:

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

In this example, I want to get line no of which <title> contains "Acknowledgments" text.

回答1:

You can do it with 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);