【问题标题】:Comment xml elements programmatically以编程方式注释 xml 元素
【发布时间】:2015-05-26 09:14:50
【问题描述】:

我有一个如下所示的 xml 文件,

<configuration>
    <property>
      <name>name</name>
      <value>dinesh</value>
    </property>
    <property>
      <name>city</name>
      <value>Delhi</value>
    </property>
</configuration>

我的要求是我需要在运行时根据属性名称以编程方式注释/取消注释属性,如下所示;

<configuration>
    <!-- <property>
      <name>name</name>
      <value>dinesh</value>
    </property> -->
    <property>
      <name>city</name>
      <value>Delhi</value>
    </property>
</configuration>

是否有任何直接的方法可以通过 XDocument / XmlDocument 遍历来实现?我刚刚从this 问题中查看了如下代码,

XmlComment DirCom = doc.CreateComment(XmlElementName.OuterXml);
doc.InsertAfter(DirCom, XmlElementName);    
doc.RemoveChild(XmlElementName)

上面的代码使用方法是否正确?

【问题讨论】:

  • 您是否尝试过任何方法来实现此目的?一些您遇到问题或遇到问题的代码?
  • 我试过 XDocument/XmlDocument 类中有没有直接的 API;但找不到相同的;我不认为这是一个如此简单的问题;即使你在谷歌中搜索,你也会得到大部分关于“Xml 文档评论”的结果;
  • 我会将 XML 转换为文本文件,然后使用 Regex 添加 cmets。我知道我会从受访者那里得到很多关于这个解决方案的噪音。在 XML 数据上使用正则表达式是非常有争议的。我通常不推荐这种解决方案,但在某些情况下,在 xml 上使用正则表达式是唯一真正的解决方案。
  • @Mivaweb 检查编辑后的答案

标签: c# xml xml-parsing


【解决方案1】:

您可以使用XDocument轻松完成此操作

var xDocument = XDocument.Parse(@"<configuration>
                                    <property>
                                      <name>name</name>
                                      <value>dinesh</value>
                                    </property>
                                    <property>
                                      <name>city</name>
                                      <value>Delhi</value>
                                    </property>
                                </configuration>");

var firstPropertyElement = xDocument
    .Descendants("property")
    .First();//Find your element
var xComment = new XComment(firstPropertyElement.ToString());//Create comment
firstPropertyElement.ReplaceWith(xComment);//Replace the element with comment 
Console.WriteLine(xDocument);

哪些输出:

<configuration>
  <!--<property>
  <name>name</name>
  <value>dinesh</value>
</property>-->
  <property>
    <name>city</name>
    <value>Delhi</value>
  </property>
</configuration>

【讨论】:

    猜你喜欢
    • 2010-11-01
    • 1970-01-01
    • 2019-07-28
    • 1970-01-01
    • 2011-10-09
    • 1970-01-01
    • 2016-12-05
    • 2012-05-31
    • 2013-07-23
    相关资源
    最近更新 更多