需要在现有的xml文档中添加注释

时间:2012-07-13 06:24:23

标签: c#

我需要在现有的xml文档中添加注释。示例xml如下所示我需要在c#中编写代码。 XML序列化用于生成此xml 任何帮助都会很棒...... 提前谢谢

<?xml version="1.0" encoding="utf-8"?>
<Person>
<Name>Job</Name>
<Address>10dcalp</Address>
<Age>12</Age>
</Person>

2 个答案:

答案 0 :(得分:11)

试试这样:

        string input = @"<?xml version=""1.0"" encoding=""utf-8""?><Person><Name>Job</Name><Address>10dcalp</Address><Age>12</Age></Person>";
        XDocument doc = XDocument.Parse(input);
        XElement age = doc.Root.Element("Age");
        XComment comm = new XComment("This is comment before Age");
        age.AddBeforeSelf(comm);

此代码获取文档,找到名为“Age”的元素,该元素应位于根元素(“Person”)下并在其前添加注释。

答案 1 :(得分:1)

您可以使用XmlWriter以下列方式撰写评论:

    MemoryStream stream = new MemoryStream();
    XmlWriter writer = XmlWriter.Create(stream);
    writer.WriteStartDocument();
    writer.WriteComment("Add comment here");

现在,您通过序列化程序序列化XmlWriter实例。