文档光标的路径是什么?

时间:2013-03-21 13:48:27

标签: c# .net xmlreader xmlwriter xmltextreader

我正在使用System.Xml.XmlTextReader仅向前读者。在调试时,我可以随时检查属性LineNumberLinePosition以查看光标的行号和列号。有什么办法可以在文档中看到光标的任何“路径”吗?

例如,在以下HTML文档中,如果光标位于*,则路径将类似于html/body/p。我发现这样的东西真有帮助。

<html>
    <head>
    </head>
    <body>
        <p>*</p>
    </body>
</html>

编辑:我也希望能够同样地检查XmlWriter

1 个答案:

答案 0 :(得分: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;
    }
}