文档光标的路径是什么?

4
我正在使用System.Xml.XmlTextReader这个只能向前读取的阅读器。调试时,我可以随时检查属性LineNumberLinePosition,以查看光标所在的行号和列号。是否有任何方法可以在文档中看到指向光标的“路径”?
例如,在以下HTML文档中,如果光标位于*处,则路径将类似于html/body/p。我认为这样的功能非常有用。
<html>
    <head>
    </head>
    <body>
        <p>*</p>
    </body>
</html>

编辑:我也希望能够类似地检查XmlWriter

1个回答

2
据我所知,您无法使用普通的XmlTextReader来做到这一点;但是,您可以通过创建一个新的Path属性来扩展它以提供此功能:
public class XmlTextReaderWithPath : XmlTextReader
{
    private readonly Stack<string> _path = new Stack<string>();

    public string Path
    {
        get { return String.Join("/", _path.Reverse()); }
    }

    public XmlTextReaderWithPath(TextReader input)
        : base(input)
    {
    }

    // TODO: Implement the other constuctors as needed

    public override bool Read()
    {
        if (base.Read())
        {
            switch (NodeType)
            {
                case XmlNodeType.Element:
                    _path.Push(LocalName);
                    break;

                case XmlNodeType.EndElement:
                    _path.Pop();
                    break;

                default:
                    // TODO: Handle other types of nodes, if needed
                    break;
            }

            return true;
        }

        return false;
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接