开发者

Indentation of XML not working as expected

开发者 https://www.devze.com 2023-02-20 06:06 出处:网络
I am trying to create an XML file using string data. (Which is itself in XML format.) But the main problem is that the XML that I have created is not properly formatted. I have used XmlWriterSettings

I am trying to create an XML file using string data. (Which is itself in XML format.) But the main problem is that the XML that I have created is not properly formatted. I have used XmlWriterSettings to format the XML, but it does not seem to be working. Can anyone tell me what is wrong with this code.

    string unformattedXml = @"<datas><data1>sampledata1</data1><datas>";

    XmlWriterSettings xmlSettingsWithIndentation = new XmlWriterSettings { Indent = true};
    using (XmlWriter writer = XmlWriter.Create(Console.Out, xmlSettingsWithIndentation))
       {

          开发者_运维技巧 writer.WriteRaw(unformattedXml);
       }

Actually when I load this string in an XmlDocument and then saves it as a file, it was formatted. I just wanted to know why it was not working with XmlWriter.

You help would be much appreciated.

Thanks, Alex


To ignore white space, try this:

private static string FormatXml(string unformattedXml) 
{
    //First read the xml, ignoring whitespace.
    var readeroptions = new XmlReaderSettings { IgnoreWhitespace = true };
    var reader = XmlReader.Create(new StringReader(unformattedXml), readeroptions);
   
    //Then write it out with indentation.
    var sb = new StringBuilder();
    var xmlSettingsWithIndentation = new XmlWriterSettings { Indent = true }; 
                  
    using (var writer = XmlWriter.Create(sb, xmlSettingsWithIndentation))
        writer.WriteNode(reader, true);
            
    return sb.ToString();
}


It should work if you use a XmlReader instead of a raw string.

(I expect it is a typo when your last XML element is not closed property, and that by formatting you refer to correct indentation):

class Program
{
    static void Main(string[] args)
    {
        string unformattedXml = @"<datas><data1>sampledata1</data1></datas>";

        var rdr = XmlReader.Create(new StringReader(unformattedXml));

        var sb = new StringBuilder();
        
        var xmlSettingsWithIndentation =  new XmlWriterSettings 
        { 
            Indent = true
        };

        using (var writer = XmlWriter.Create(sb, xmlSettingsWithIndentation))
            writer.WriteNode(rdr, true);
        
        Console.WriteLine(sb);
        Console.ReadKey();
    }
}

It outputs:

<?xml version="1.0" encoding="utf-16"?>
<datas>
  <data1>sampledata1</data1>
</datas>

Please cf. similar questions:
XmlWriter.WriteRaw indentation
XML indenting when injecting an XML string into an XmlWriter

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号