简体   繁体   中英

Is it possible to get line numbers/positions from a System.Xml.XmlNode when working with a System.Xml.XmlDocument?

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

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

You can do this using the IXmlLineInfo interface .

I know that with XDocument and XPathDocument you can just cast a node to IXmlLineInfo . I think its also possible with XmlDocument.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM