使用C#取消注释XML文件中的注释节点

Ana*_*nth 6 c# xml xmldom

我有一个XML文件,其中有一个被注释掉的节点.我使用语法创建了这个节点 -

relTableCommentedNode = xDoc.CreateNode(XmlNodeType.Comment,"RELTABLECOMMENTED","np");

取消注释此节点的最佳方法是什么?我可以根据用于创建节点的名称(RELTABLECOMMENTED)来识别此节点吗?

这是注释节点

 
<!--<reltable toc="no" class="- map/reltable ">
    <relheader class="- map/relheader ">
      <relcolspec type="concept" class="- map/relcolspec ">      
    </relheader>
    <relrow class="- map/relrow ">
      <relcell class="- map/relcell ">
        <topicref href="concepts\about_cannedgoods.dita" copy-to="concepts\about_cannedgoods.dita" class="- map/topicref " xmlns:dctm="http://www.documentum.com">
        </topicref>
      </relcell>      
    </relrow>
  </reltable> -->

Chr*_*lor 9

To the best of my knowledge, using XmlDocument, there is no direct way to do this. You will need to do something like the following

  1. Get the value of the comment node
  2. Create a new XmlNode with the value from step 1
  3. 删除注释节点
  4. 将步骤2中的新节点添加到DOM树中

下面是一个示例,其中包含XML的略微简化版本,并在有关查找正确注释节点的注释中解决您的问题.请注意,我查询所有注释节点,显然您可以更具体,并查询您感兴趣的文档部分.

  string xml = @"
    <root>
      <!--<reltable toc='no' class='- map/reltable '>
      <relheader class='- map/relheader '>
        <relcolspec type='concept' class='- map/relcolspec '/>      
      </relheader>         
    </reltable> -->

    <!--<reltable toc='no' class='- map '>
      <relheader class='- map/relheader '>
        <relcolspec type='concept' class='- map/relcolspec '/>      
      </relheader>          
    </reltable> -->
  </root>";

  XmlDocument xdoc = new XmlDocument();
  xdoc.LoadXml(xml);

  XmlNodeList commentedNodes = xdoc.SelectNodes("//comment()");
  var commentNode = (from comment in commentedNodes.Cast<XmlNode>()
              where comment.Value.Contains("class='- map '")
              select comment).FirstOrDefault();

  if (commentNode != null)
  {
    XmlReader nodeReader = XmlReader.Create(new StringReader(commentNode.Value));
    XmlNode newNode = xdoc.ReadNode(nodeReader);
    commentNode.ParentNode.ReplaceChild(newNode, commentNode);
  }
Run Code Online (Sandbox Code Playgroud)