Search code examples
.netxmlxmldocument

XmlDocument don't save white spaces between tags


Part of XML:

<text:p>text1 <text:span>text2</text:span> <text:span>text3</text:span>text4</text:p>

You can see a space between text:span tags with text2 and text3. When I call XmlDocument.Load method I have this picture:

<text:p>text1 <text:span>text2</text:span><text:span>text3</text:span>text4</text:p>

White space was removed, but I need this space in this place. Set property "PreserveWhitespace = true" don't help


Solution

  • PreserveWhitespace works for me. My sample code is

        string xml = "<root><p>text1 <span>text2</span> <span>text3</span>text4</p></root>";
        XmlDocument doc = new XmlDocument();
        doc.PreserveWhitespace = true;
        doc.LoadXml(xml);
    
        Console.Write(doc.InnerXml);
    

    This prints

    <root><p>text1 <span>text2</span> <span>text3</span>text4</p></root>
    

    with the space between the span elements still there.