How to force XDocument to output the prolog in uppercase while preserving identation and formatting?

前端 未结 4 1856
刺人心
刺人心 2021-01-23 05:34

I want XDocument to output the XML prolog (for example \"\") in uppercase.

Here is how I\'m cur

4条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-23 06:14

    Here is a sample solution using XmlTextWriter

    I am sure there should be a better optimal way..

                XDocument doc = new XDocument(new XDeclaration("1.0", "UTF-8","d"));
                doc.Add(new XElement("MyRoot", "Value blah"));
    
    
                using (var str = new StringWriter())
                using (var xmlTextWriter = new XmlTextWriter(str))
                {
                    xmlTextWriter.Formatting = Formatting.Indented;
                    xmlTextWriter.Indentation = 4;
    
                    xmlTextWriter.WriteRaw(doc.Declaration.ToString().ToUpper());
    
                    foreach (var xElement in doc.Elements())
                    {
                       xmlTextWriter.WriteElementString(xElement.Name.ToString(), xElement.Value);
                    }
    
                    var finalOutput = str.ToString();
                }
    

    FinalOutput would contain:

    
    Value blah
    

提交回复
热议问题