Reputation: 123
I need to add comments in an existing xml document.a sample xml is shown below i need to write code in c#. XML serialization was used to generate this xml any help would be great... thanks in advance
<?xml version="1.0" encoding="utf-8"?>
<Person>
<Name>Job</Name>
<Address>10dcalp</Address>
<Age>12</Age>
</Person>
Upvotes: 8
Views: 8189
Reputation: 8832
Try it like this:
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);
This code gets the document, finds the element named "Age" which is expected to be under the root element ("Person") and adds comment before it.
Upvotes: 13
Reputation: 16310
You can use XmlWriter
to write the comment in following way:
MemoryStream stream = new MemoryStream();
XmlWriter writer = XmlWriter.Create(stream);
writer.WriteStartDocument();
writer.WriteComment("Add comment here");
Now, you serialize XmlWriter
instance through your serializer.
Upvotes: 1