score:2
Formatting of XML output is controlled by XmlWriter
not XElement
or XDocument
, so if you need precise control of formatting you will need to create your own writer by subclassing one of the implementations of XmlWriter
, specifically XmlTextWriter
whose Formatting
property is mutable and can be changed during writing.
For instance, here is a version that disables indentation when the element depth exceeds 1:
public class CustomFormattingXmlTextWriter : XmlTextWriter
{
readonly Stack<Formatting> stack = new Stack<Formatting>();
public CustomFormattingXmlTextWriter(TextWriter writer, int indentDepth) : base(writer)
{
this.Formatting = Formatting.Indented;
this.IndentDepth = indentDepth;
}
int IndentDepth { get; }
void OnElementStarted(string localName, string ns)
{
stack.Push(Formatting);
// You could e.g. modify the logic here to check to see whether localName == CHILDELEMENT
// if (localName == "CHILDELEMENT")
if (stack.Count == IndentDepth+1)
Formatting = Formatting.None;
}
void OnElementEnded()
{
var old = stack.Pop();
if (old != Formatting)
Formatting = old;
}
public override void WriteStartElement(string prefix, string localName, string ns)
{
base.WriteStartElement(prefix, localName, ns);
OnElementStarted(localName, ns);
}
public override void WriteEndElement()
{
base.WriteEndElement();
OnElementEnded();
}
public override void WriteFullEndElement()
{
base.WriteEndElement();
OnElementEnded();
}
}
public static partial class XNodeExtensions
{
public static void SaveWithCustomFormatting(this XDocument doc, string filename, int indentDepth)
{
using (var textWriter = new StreamWriter(filename))
using (var writer = new CustomFormattingXmlTextWriter(textWriter, indentDepth))
{
doc.Save(writer);
}
}
}
Using it, you can do:
myDoc.SaveWithCustomFormatting(fileName, 1);
which outputs, as required:
<ROOTELEMENT>
<CHILDELEMENT><INFO1>Test a 1</INFO1><INFO2>Test a 2</INFO2></CHILDELEMENT>
<CHILDELEMENT><INFO1>Test b 1</INFO1><INFO2>Test b 2</INFO2></CHILDELEMENT>
</ROOTELEMENT>
Notes:
You can modify the logic in
CustomFormattingXmlTextWriter.OnElementStarted()
to disable the formatting using any criteria you desire such as checking to see whether the incominglocalName
isCHILDELEMENT
.XmlTextWriter
is deprecated in favor ofXmlWriter
-- but the latter does not have a mutableFormatting
property. If you must needs useXmlWriter
you might look at Is there a way to serialize multiple XElements onto the same line?.
Demo fiddle #1 here.
Source: stackoverflow.com
Related Articles
- XDocument write specific XElement in a single line
- linqpad hide specific column or restrict row to single line
- C# Linq / How to write below code in single query?
- string.contains and string.replace in one single line of code
- How to join two arrays in C# using a single line of code
- List or Array of String Contain specific word in Html Source Code
- Using XPath within a single XElement to find only nodes that has a child node with specific Attribute
- c# Linq or code to extract groups from a single list of source data
- Convert string[] to int[] in one line of code using LINQ
- Edit specific Element in XDocument
- how to add XElement in specific location in XML Document
- How to get specific element Count in XML or XElement variable
- Flatten List<string[]> into single string with one line for each element
- LINQ Source Code Available
- Selecting a XElement from a XDocument
- how do I write LINQ query to retrieve distinct records based on only specific properties?
- .NET 4 Code Contracts: "requires unproven: source != null"
- Removing a single item from an enumerable source when the items are equal
- How can I write the following code more elegantly using LINQ query syntax?
- How do I write this loop as a single line?
- Querying a specific line from a txt file in C#
- Parsing delimited data for specific instance of repeated line
- difference between XElement and XDocument
- Copy a list of objects to another typed list in one line of code
- Inserting particular XElement at specific position in a XML using LINQ
- creating Linq to sqlite dbml from DbLinq source code
- Duplicate elements when adding XElement to XDocument
- Adding 90000 XElement to XDocument
- How to flatten a multi level XML into a single level XML using c# code LINQ
- Remove an XElement from another XDocument
- how to select records from multiple table with max count value from one table using Linq in Asp.net MVC C#
- How to get a distinct list from a List of objects?
- Grouping and nesting list with LINQ
- How to find the top number between a range given a value from a table using LINQ
- Can I use LINQ to create a new list of objects from an existing list
- selecting a set of objects based on index linq
- Creating Extension method to include subquery
- LINQ group by sum not working as expected
- Linq - Sum with isnull
- Is order of the predicate important when using LINQ?
- C# Linq Query group by check if result is null
- How to use left outer join in LINQ for SQL query?
- How do lambdas inside linq functions type parameters work?
- Trouble with linq query on a Dictionary<string, Dictionary<string, int>>
- c# get list of users that have a specific foreign key
- Operand '==' cannot be applied for operands of type bool and string
- return the length of the shortest word(s)
- Group By from DataTable using linq
- How to Check Whether an Array (or List) Contains Another an Array (List) Using LINQ
- How to Remove elements from one List based another list's element and condition?