xmlreader newline \n instead of \r\n

后端 未结 5 1633
不思量自难忘°
不思量自难忘° 2021-01-11 11:32

When I use XmlReader.ReadOuterXml(), elements are separated by \\n instead of \\r\\n. So, for example, if I have XmlDocument representatino of


<         


        
5条回答
  •  鱼传尺愫
    2021-01-11 11:39

    There's a quicker way if you're just trying to get to UTF-8. First create a writer:

    public class EncodedStringWriter : StringWriter
    {
        public EncodedStringWriter(StringBuilder sb, Encoding encoding)
            : base(sb)
        {
            _encoding = encoding;
        }
    
        private Encoding _encoding;
    
        public override Encoding Encoding
        {
            get
            {
                return _encoding;
            }
        }
    
    }
    

    Then use it:

    XmlDocument doc = new XmlDocument();
    doc.LoadXml("");
    
    StringBuilder sb = new StringBuilder();
    XmlWriterSettings xws = new XmlWriterSettings();
    xws.Indent = true;
    
    using( EncodedStringWriter w = new EncodedStringWriter(sb, Encoding.UTF8) )
    {
        using( XmlWriter writer = XmlWriter.Create(w, xws) )
        {
            doc.WriteTo(writer);
        }
    }
    string xml = sb.ToString();
    

    Gotta give credit where credit is due.

提交回复
热议问题