如何使用 System.XML 在 C# 中注释 XML 文件的一行 [英] How to comment a line of a XML file in C# with System.XML

查看:38
本文介绍了如何使用 System.XML 在 C# 中注释 XML 文件的一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to comment and uncomment the 4th line of this XML file using System.XML properties:

<?xml version="1.0" encoding="utf-8"?>
    <configuration>    
        <system.web>
            <customErrors mode="On" defaultRedirect="som_url_here" />
        </system.web>
    </configuration>

所需的输出:

<!-- <customErrors mode="On" defaultRedirect="som_url_here" /> -->

是否可以在不使用文件阅读器的情况下实现这一点?

It's possible to achieve this without using a file reader?

节点:

XmlNode xmlNodoCE = docWebConfig.DocumentElement.SelectSingleNode("system.web/customErrors");

推荐答案

您需要

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

  • load the file into an XmlDocument,
  • retrieve the node you want to comment,
  • create a comment node containing the XML content of your original node,
  • add this comment to the original's parent node just before the original node
  • remove it from its parent,
  • write the XmlDocument to a file (the same one).

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);

这篇关于如何使用 System.XML 在 C# 中注释 XML 文件的一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆