Accessing Comments in XML using XPath

With the path

/foo/bar/comment()

you can select all comments in the /foo/bar element. May depend on your language of choice, of course. But generally this is how you do it.


Use comment() function for example:-

/table/length/following::comment()[1]

selects the first comment that follows the length element.

Edit

Manoj asks in a comment to this answer why this isn't working in MSXML. The reason will be you are using MSXML3. By default MSXML3 does not use XPath as its selection language, it defaults to an earlier much weaker language (XSL pattern). You need to set XPath as the selection language via the DOMDocument's setProperty method. E.g (in JScript):-

var dom = new ActiveXObject("MSXML2.DOMDocument.3.0");
dom.setProperty("SelectionLanguage", "XPath");

Now the full XPath language will work in your queries (note one breaking change is indexer predicates are 1 based in XPath whereas they were 0 based in XSL Pattern).


Based on the OP's comments to posted answers (and my curiosity as to why this simple thing would not work), here is my suggestion:

Using the XPath expression suggested by @Anthony, I was able to successfully load the comment node with the following JS function:

function SelectComment(s)
{
  var xDoc = new ActiveXObject("MSXML2.DOMDocument.6.0");
  if (xDoc)
  {
    xDoc.loadXML(s);
    var selNode = xDoc.selectSingleNode("/table/length/following::comment()[1]");
    if (selNode != null)
      return selNode.text;
    else
      return "";
  }
}

Sample invocation:

SelectComment("<table><length> 12</length><!--Some comment here--></table>");

Output:

"Some comment here"

Notes:

a. Your MSXML version may vary. Please use appropriately.

b. This kind of code is definitely not recommended because it works only on IE. However, since this is your explicitly stated requirement, I have used the ActiveXObject.

c. You have not mentioned in your comments what fails in the suggested XPath expressions. My guess is that you are not querying the text property of the retrieved node. Keep in mind that the SelectSingleNode always returns an IXmlNode and you need to query its data or text properties.


Maybe this coud help, This sample removes Comments

XmlNodeList list = xmlDoc.SelectNodes("//comment()");
foreach(XmlNode node in list)
node.ParentNode.RemoveChild(node);

Leaned from here link text