views:

137

answers:

1

I have an XML document, want to do syntax highlighting.

The code uses XPathDocument, XPathNavigator and XPathNodeIterator . After I call Select(), how can I get the original text in the XML document?

var xpathDoc = new XPathDocument(new StringReader(this.richTextBox1.Text));
var nav = xpathDoc.CreateNavigator();
XmlNamespaceManager xmlns = new XmlNamespaceManager(nav.NameTable);
xmlns.AddNamespace("ns1", "urn:myxnlnamespace");
XPathNodeIterator selection = nav.Select(xpathExpression, xmlns);

foreach (XPathNavigator node in selection)
{
   // Here, node.OuterXml includes an explicit namespace.
   // If the original raw xml fragment for this node was
   //    <ElementName>Text</ElementName>
   // and if xmlns="urn:myxnlnamespace" is used on the root of the document....
   //
   // OuterXml will return
   //    <ElementName xmlns="urn:myxnlnamespace">Text</ElementName>
   //
   // InnerXml will return "Text" in this example. 
   // 
   // How can I get the original, raw XML bytestream for this node?
   // Like this:
   //    <ElementName>Text</ElementName>
   //
}

It would also work, for me, to get the IXmlLineInfo of both the beginning and the end of the selected node. Right now I can move to the beginning of the selected node and get the IXmlLineInfo for that. But I know only how to move to the next node (MoveToNext()); Don't know how to move to the end of the current node. Also this approach doesn't work if the node in question is the last in a sequence (no more siblings).

It would also work if there was some xpath expression that returned the full raw text of the current node. So far I can't find something like that, either.


EDIT: I moved beyond this problem via a shameless hack. To determine the length of the text I need to highlight, I parse the original xml text manually, searching for angle brackets and name tokens. It isn't pretty but in the absence of something better, it works for simple XML files.

I'm still interested in a real answer, if anyone has one.

A: 

You may find useful the way the XPath Visualizer performs syntax hilighting of an XML document.

Dimitre Novatchev
Thanks, Dimitre. Your tool has been around a loooong time, eh? I wanted my own so I built one. http://XpathVisualizer.codeplex.com I came upon this question while trying to get highlighting to work.
Cheeso
@Cheeso I don't think there is a significantly better solution to this than what IE has been offering for the last 9-10 years. This is why I recommend the XPath Visualizer's way of doing it, which is essentially an adaptation of the IE's stylesheet, so that it is now written in compliant XSLT 1.0 (not in the Microsoft's older xsl dialect).
Dimitre Novatchev