How to enable declaration using XElement.ToString ()

I am trying to write an XML response for my web service, but I cannot figure out how to make an ad in response.

My code looks like this:

StringBuilder sBuilder = new StringBuilder(); using (XmlWriter writer = XmlWriter.Create(sBuilder)) { writer.WriteStartDocument(); writer.WriteStartElement("ReportResponse"); Response.WriteXml(writer); writer.WriteEndElement(); writer.WriteEndDocument(); } var response = XElement.Parse(sBuilder.ToString()); return response; 

The response is just a POCO for storing response data.

I know that the Save method includes the declaration, while the ToString() method does not. I need to write my declaration using ToString() .

I just want to return custom XML from my REST service without changing my string 100 times to return the correct XML. Is this possible, or am I just spinning my wheels?

+6
source share
1 answer

If you want to include an xml declaration, you can do it like this:

 XDocument xdoc = XDocument.Parse(xmlString); StringBuilder builder = new StringBuilder(); using (TextWriter writer = new StringWriter(builder)) { xdoc.Save(writer); } Console.WriteLine(builder); 

Update: I noticed that StringWriter is messing up the encoding. So another option:

 string docWithDeclaration = xdoc.Declaration + xdoc.ToString(); 
0
source

Source: https://habr.com/ru/post/904550/


All Articles