1

I am building an XML string programatically using the XmlWriter ...

sb = New StringBuilder()
writer = XmlWriter.Create(sb)

writer.WriteStartDocument()
writer.WriteStartElement("root")

writer.WriteStartElement("element1")
writer.WriteAttributeString("myattribute", "myvalue")
writer.WriteEndElement()

writer.WriteEndElement()
writer.WriteEndDocument()

writer.Flush()

myTextBox.text = "<pre>" & Return sb.ToString() & "</pre>"

I want to be able to output the XML to a TextBox control on a ASP.NET webform. When I do output the XML I don't get any line breaks or indentation in the XML. The XmlWriter does not seem to have any properties to set formatting. Is there anyway to retain formatting and indentation? Thank you.

2 Answers 2

3

Use a XmlWriterSettings class instance to specify the use of indentations and line breaks and then pass it into the xmlWriter's Create method. See the documentation here.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the link to the documentation. Good example listed there.
0

try this

  StringBuilder sb = new StringBuilder();
        StringWriter sw = new StringWriter();
        XmlTextWriter writer = new XmlTextWriter(sw);

        writer.Formatting = Formatting.Indented;


        // Write Xml Declaration with version 1.0 
        writer.WriteStartDocument();


        // Write Xml Document Root Element
        writer.WriteStartElement("Product");


        // Write attribute name and value to current Element 
        writer.WriteAttributeString("ProductID", "01");


        // Write Xml Element with Name and Inner Text
        writer.WriteElementString("ProductName", "P-Name");
        writer.WriteElementString("ProductQuantity","P-Quantity");
        writer.WriteElementString("ProductPrice", "P-Price");

        // Write Product Element closing Tag
        writer.WriteEndElement();

        // Write End of Document 
        writer.WriteEndDocument();

        // Flush and Close Writer
        writer.Flush();

        textBox1.Text = sw.ToString();

1 Comment

-1: Don't use new XmlTextWriter(). It has been deprecated since .NET 2.0. Use XmlWriter.Create() instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.