Frank Lioty
Frank Lioty

Reputation: 977

XML new lined inner text

I'm working with XMLs and I have this problem: I want to add an inner text on a single line separated by opening and closing element tags. Something like this:

<root>
 <child name="name">
  Hi! I'm inner text!
 </child>
</root>

but if I add the inner text with:

child.InnerText = "Hi! I'm inner text!";

I have all on the same line:

<root>
 <child name="name">Hi! I'm inner text!</child>
</root>

I tried to add:

xDoc.PreserveWhitespace = true;

before Save function with no result. Tried with:

child.AppendChild(xDoc.CreateWhitespace("\n"));

after or before the InnerText instruction. Nothing. Some help?

EDIT: This is how I save the XML:

xDoc.Save(filename);

Upvotes: 1

Views: 2505

Answers (1)

MNGwinn
MNGwinn

Reputation: 2394

There are a couple of different options. You can set InnerText of the XmlElement or append a text node.

XmlDocument xDoc = new XmlDocument();
xDoc.PreserveWhitespace = true;

XmlNode root = xDoc.AppendChild(xDoc.CreateElement("root"));
XmlNode child = root.AppendChild(xDoc.CreateElement("child"));

((XmlElement)child).InnerText = "\nHi! I'm Inner Text!\n";
child.AppendChild(xDoc.CreateTextNode("\nHi! I'm also Inner Text\n"));
xDoc.Save(@"c:\temp\temp.xml");
Debug.Write(xDoc.InnerXml.ToString());

Keep in mind that, depending on how you look at the generated XML, you may not see the newlines produced in the document. IE, for example, will happily ignore them when showing you the pretty version of the document.

Upvotes: 1

Related Questions