The title says it all...
Is it possible to get line numbers/positions from a System.Xml.XmlNode
when working with a System.Xml.XmlDocument
?
I want the information so that I can inform the user of where they need to look in their Xml file for specific pieces of information. I've seen similar questions relating to an XmlReader
on SO but nothing that actually answers my question.
I guess I could search the xml file for the OuterXml
of the node that I'm interested in, but that seems hacky, and what if that information appears in the file more than once? There must be a better way?
Update: I'm loading my xml file using:
xmlDoc = new XmlDocument();
xmlDoc.PreserveWhitespace = true;
xmlDoc.Load(filename);
XDocument is from the LINQ to XML API, and XmlDocument is the standard DOM-style API for XML. If you know DOM well, and don't want to learn LINQ to XML, go with XmlDocument . If you're new to both, check out this page that compares the two, and pick which one you like the looks of better.
Load(XmlReader) Loads the XML document from the specified XmlReader.
XmlNode is the base class in the . NET implementation of the DOM. It supports XPath selections and provides editing capabilities. The XmlDocument class extends XmlNode and represents an XML document. You can use XmlDocument to load and save XML data.
The XmlReader class in C# provides an efficient way to access XML data. XmlReader. Read() method reads the first node of the XML file and then reads the whole file using a while loop.
I'm not sure if this is going to help someone, but I had similar objective to the OP. In my particular case, I have an XmlDocument and I needed to have the line number of all the Textbox nodes. Since I was getting the same Exception MadSkunk described, I figured that the only was to create an XPathDocument instance and do the casting.
Richard Schneider's answer helped me to visualise that. So my current method looks like this:
public Dictionary<int, string> GetLineNumber()
{
Dictionary<int, string> attrByLineNumber = new Dictionary<int, string>();
MemoryStream xmlStream = new MemoryStream();
_xmlDoc.Save(xmlStream);
xmlStream.Position = 0;
XPathDocument pathDocument = new XPathDocument(xmlStream);
foreach (XPathNavigator element in pathDocument.CreateNavigator().Select("//*"))
{
if (element.Name.Equals("Textbox"))
{
attrByLineNumber.Add(((IXmlLineInfo)element).LineNumber, element.GetAttribute("Name", ""));
}
}
return attrByLineNumber;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With