如何使用System.XML在C#中注释XML文件的一行

Nov*_*ovo 9 c# xml

我需要使用System.XML属性注释和取消注释此XML文件的第4行:

<?xml version="1.0" encoding="utf-8"?>
    <configuration>    
        <system.web>
            <customErrors mode="On" defaultRedirect="som_url_here" />
        </system.web>
    </configuration>
Run Code Online (Sandbox Code Playgroud)

期望的输出:

<!-- <customErrors mode="On" defaultRedirect="som_url_here" /> -->
Run Code Online (Sandbox Code Playgroud)

不使用文件阅读器就可以实现这一目标吗?

节点:

XmlNode xmlNodoCE = docWebConfig.DocumentElement.SelectSingleNode("system.web/customErrors");
Run Code Online (Sandbox Code Playgroud)

Sam*_*ang 10

你需要

  • 将文件加载到XmlDocument中,
  • 检索要评论的节点,
  • 创建一个包含原始节点的XML内容的注释节点,
  • 将此注释添加到原始节点之前的原始父节点
  • 从父母那里删除它,
  • 将XmlDocument写入文件(同一个文件).

    String xmlFileName = "Sample.xml";
    
    // Find the proper path to the XML file
    String xmlFilePath = this.Server.MapPath(xmlFileName);
    
    // Create an XmlDocument
    System.Xml.XmlDocument xmlDocument = new System.Xml.XmlDocument();
    
    // Load the XML file in to the document
    xmlDocument.Load(xmlFilePath);
    
    // Get the target node using XPath
    System.Xml.XmlNode elementToComment = xmlDocument.SelectSingleNode("/configuration/system.web/customErrors");
    
    // Get the XML content of the target node
    String commentContents = elementToComment.OuterXml;
    
    // Create a new comment node
    // Its contents are the XML content of target node
    System.Xml.XmlComment commentNode = xmlDocument.CreateComment(commentContents);
    
    // Get a reference to the parent of the target node
    System.Xml.XmlNode parentNode = elementToComment.ParentNode;
    
    // Replace the target node with the comment
    parentNode.ReplaceChild(commentNode, elementToComment);
    
    xmlDocument.Save(xmlFilePath);
    
    Run Code Online (Sandbox Code Playgroud)