This has got to be such a simple question but I just can't get the answer.
I have an XmlNode and all I want to do is output this node, as a string, with indentations (tabs or spaces) intact to provide better readability.
So far I tried XmlWriter, XmlTextWriter, XmlDocument, XmlReader.
To output the XmlNode as string WITHOUT indentation is easy. I just do XmlNode.OuterXml. How do I get the indentations in there?
I want to do this without looping through the XmlNode and using brute force to add whitespace, because I think there should be a simpler way.
Thanks.
Edit: For future readers, here is the answer:
var xmlNode = is some object of type XmlNode using (var sw = new StringWriter()) { using (var xw = new XmlTextWriter(sw)) { xw.Formatting = Formatting.Indented; xw.Indentation = 2; //default is 1. I used 2 to make the indents larger. xmlNode.WriteTo(xw); } return sw.ToString(); //The node, as a string, with indents! }
The reason I needed to do this was output the node's xml with syntax highlighting. I used AvalonEdit to highlight the xml, outputted the highlighted text to html, then converted the html to a FlowDocument which could be displayed in a RichTextBox.
The not-equal-to operator ( != ) returns true if the operands don't have the same value; otherwise, it returns false .
In mathematics, the tilde often represents approximation, especially when used in duplicate, and is sometimes called the "equivalency sign." In regular expressions, the tilde is used as an operator in pattern matching, and in C programming, it is used as a bitwise operator representing a unary negation (i.e., "bitwise ...
Summary. An operator is a symbol which operates on a variable or value. There are types of operators like arithmetic, logical, conditional, relational, bitwise, assignment operators etc. Some special types of operators are also present in C like sizeof(), Pointer operator, Reference operator etc.
You were on the right path with the XMLTextWriter
, you simply need to use a StringWriter
as the base stream. Here are a few good answers on how this is accomplished. Pay particular attention to the second answer, if your encoding needs to be UTF-8.
Edit:
If you need to do this in multiple places, it is trivial to write an extension method to overload a ToString()
on XmlNode
:
public static class MyExtensions { public static string ToString(this System.Xml.XmlNode node, int indentation) { using (var sw = new System.IO.StringWriter()) { using (var xw = new System.Xml.XmlTextWriter(sw)) { xw.Formatting = System.Xml.Formatting.Indented; xw.Indentation = indentation; node.WriteContentTo(xw); } return sw.ToString(); } } }
If you don't care about memory or performance, the simplest thing is:
XElement.Parse(xmlNode.OuterXml).ToString()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With