I'm using System.Xml.XmlTextReader the forward-only reader. When debugging, at any time I can check the properties LineNumber
and LinePosition
to see the line number and column number of the cursor. Is there any way I can see any kind of "path" to the cursor with in the document?
For example, in the following HTML document, if the cursor were at *, then the path would be something like html/body/p
. I'd find something like this really helpful.
<html>
<head>
</head>
<body>
<p>*</p>
</body>
</html>
Edit: I'd also like to be able to inspect XmlWriter
similarly.
As far as I know you can't do that with a plain XmlTextReader; you may, however, extend it to provide this feature by way of a new Path
property:
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;
}
}