0

I wonder if there is a way to get the XmlNode of an xml document knowing that i have the line number, i use C# and i don't want to use Linq (XDocument) I need to get the XmlNode from a XmlDocument. For exemple if i have this XML :

<Document>
<a key="1">AAA</a>
<a key="2">Aa</a>
<a key="3">aaA></a>
<a key="4">aA></a>
<b key="15">BbbB></b>
</Document>

I excepect to have a function that that take as input the line number 4 and return

<a key="3">aaA></a>

All that without using LINQ (Only using XmlDocument and XmlNode syntaxes...and not XDocument..) Thank in advance


To be more specific i need the balise and not the line for exemple If the Xml is like that :

1. <Document>
2. <a key="1">AAA</a>
3. <a key="2">Aa</a>
4. <a key="3">
5. aaA
6. </a>
7. <a key="4">aA></a>
8. <b key="15">BbbB></b>
9. </Document>

I excepect to have a function that that take as input the line number 4 or 5 or 6 it will return :

<a key="3">aaA</a>
BenMorel
  • 34,448
  • 50
  • 182
  • 322
Youssef DAOUI
  • 329
  • 1
  • 6
  • If you want to do it by line number, dont parse it as XML, parse it as a text file. Then pull out the string you want via index and parse that. In your example, the line number you want is 5. Unless you are suggesting that you want the 4th line of the node in which case now your parsing xml. – crthompson Sep 09 '14 at 17:10
  • 1
    If you need to select items by line info you may have to resort to using `XmlReader`. Check out http://stackoverflow.com/questions/621059/current-line-number-from-a-system-xml-xmlreader-c-net and [MSDN ILineInfo](http://msdn.microsoft.com/en-US/library/system.xml.ixmllineinfo.aspx). – Alexei Levenkov Sep 09 '14 at 17:16

1 Answers1

0

You could just do this by reading the string text in and grabbing the lines you want too. But then it is just a string and not a XmlNode.

To do it with a XmlDocument you need to select the root node, and index the children of that node -1 for the line the node is taking.

        XmlNode root = doc.SelectSingleNode("//Document");
        XmlNode nodeIWant = root.ChildNodes[line - 1];
Jeffrey Wieder
  • 2,336
  • 1
  • 14
  • 12
  • While your sample works for text provided by OP, it is not valid approach in general as there is no connection between XML nodes and line numbers. – Alexei Levenkov Sep 09 '14 at 17:21
  • I understand that, that is why my first suggestion was to read the text lines from the file. I was also giving him a solution for the way he asked it to be done. – Jeffrey Wieder Sep 09 '14 at 17:23