Indentation and new line command for XMLwriter in C#

Use a XmlTextWriter instead of XmlWriter and then set the Indentation properties. Example string filename = “MyFile.xml”; using (FileStream fileStream = new FileStream(filename, FileMode.Create)) using (StreamWriter sw = new StreamWriter(fileStream)) using (XmlTextWriter xmlWriter = new XmlTextWriter(sw)) { xmlWriter.Formatting = Formatting.Indented; xmlWriter.Indentation = 4; // … Write elements } Following @jumbo comment, this could also be … Read more

Writing XML attributes and namespace declarations in a specific order

XML attribute and namespace declaration order should never matter Attribute order is insignificant per the XML Recommendation: Note that the order of attribute specifications in a start-tag or empty-element tag is not significant. Namespace declaration are like attributes (W3C Namespaces in XML Recommendation, section 3 Declaring Namespaces), [Definition: A namespace (or more precisely, a namespace … Read more

How to put an encoding attribute to xml other that utf-16 with XmlWriter?

You need to use a StringWriter with the appropriate encoding. Unfortunately StringWriter doesn’t let you specify the encoding directly, so you need a class like this: public sealed class StringWriterWithEncoding : StringWriter { private readonly Encoding encoding; public StringWriterWithEncoding (Encoding encoding) { this.encoding = encoding; } public override Encoding Encoding { get { return encoding; … Read more

Create XML in JavaScript

Disclaimer: The following answer assumes that you are using the JavaScript environment of a web browser. JavaScript handles XML with ‘XML DOM objects’. You can obtain such an object in three ways: 1. Creating a new XML DOM object var xmlDoc = document.implementation.createDocument(null, “books”); The first argument can contain the namespace URI of the document … Read more

Custom xmlWriter to skip a certain element?

Found this in some sample code I wrote previously. It maintains a push-down stack to determine whether to write the element end, which is what you would need to do: public class ElementSkippingXmlTextWriter : XmlWriterProxy { readonly Stack<bool> stack = new Stack<bool>(); readonly Func<string, string, int, bool> filter; readonly Func<string, string, int, string> nameEditor; readonly … Read more

Appending an existing XML file with XmlWriter

you can use Linq Xml XDocument doc = XDocument.Load(xmlFilePath); XElement school = doc.Element(“School”); school.Add(new XElement(“Student”, new XElement(“FirstName”, “David”), new XElement(“LastName”, “Smith”))); doc.Save(xmlFilePath); Edit if you want to add Element to Existing <Student>, just add an Attribute before school.add(new XElement(“Student”, new XAttribute(“ID”, “ID_Value”), new XElement(“FirstName”, “David”), new XElement(“LastName”, “Smith”))); Then you can add further Details to … Read more