C# 以编程方式注释xml元素
我有一个如下所示的xml文件C# 以编程方式注释xml元素,c#,xml,xml-parsing,C#,Xml,Xml Parsing,我有一个如下所示的xml文件 <configuration> <property> <name>name</name> <value>dinesh</value> </property> <property> <name>city</name> <value>Delhi</value>
<configuration>
<property>
<name>name</name>
<value>dinesh</value>
</property>
<property>
<name>city</name>
<value>Delhi</value>
</property>
</configuration>
上述代码使用方法正确吗?使用
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);
var xDocument=xDocument.Parse(@)
名称
迪内希
城市
德里
");
var firstPropertyElement=xDocument
.后代(“财产”)
.First()//找到你的元素
var xComment=new xComment(firstPropertyElement.ToString())//创建注释
firstPropertyElement.替换为(xComment)//用注释替换元素
Console.WriteLine(xDocument);
哪些产出:
<configuration>
<!--<property>
<name>name</name>
<value>dinesh</value>
</property>-->
<property>
<name>city</name>
<value>Delhi</value>
</property>
</configuration>
城市
德里
您是否尝试过实现这一点?一些代码被卡住了或遇到了问题?我试过XDocument/XmlDocument类中是否有任何直接API;但是找不到同样的;我不认为这是一个如此简单的问题;即使你在谷歌搜索,你也会得到关于“Xml文档评论”的大部分结果;我将把XML放在一个文本文件中,然后使用正则表达式添加注释。我知道我会从受访者那里听到很多关于这个解决方案的噪音。在XML数据上使用正则表达式是非常有争议的。我通常不推荐这种解决方案,但在某些情况下,在xml上使用正则表达式是唯一真正的解决方案。@Mivaweb检查编辑的答案
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>