4

我正在使用System.Xml.XmlTextReader只进阅读器。调试时,我可以随时查看属性LineNumberLinePosition查看光标的行号和列号。有什么方法可以在文档中看到光标的任何“路径”?

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

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

编辑:我也希望能够进行XmlWriter类似的检查。

4

1 回答 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;
    }
}
于 2013-03-21T21:46:55.643 回答