Home>

We have created a program that outputs an XML file in C #.
I am in trouble because I cannot create the following record.
Example:
<Learn more>
<Food Expenses>10000 Yen
<Comment>TEST</Comment>
</Food Expenses>
</Learn more>

<Food Expenses>I want to insert a line break after 10,000 yen, but it doesn't work.

Error message

Sometimes I've just started working with XML files, but the value is not between tags,
There are a value and a line break next to the tag.

Applicable source code
var xml = New XElement ("Details", New XElement ("Food Expenses", "10000 Yen", New XElement ("Comment", "TEST")))
'The above code will output the following:
'&lt;Details&gt;
  '&lt;Food Expenses&gt;10000 Yen&lt;Comments&gt;TEST&lt;/Comments&gt;&lt;/Food Expenses&gt;
'&lt;/Details&gt;
‘If above output&lt;Food Expenses&gt;10000 Yen (without line feed)&lt;Comments&gt;TEST&lt;/Comments&gt;(No line breaks)&lt;/Food Expenses&gt;
var xml = New XElement ("Details", New XElement ("Food Expenses", "10000 Yen"&amp;Environment.NewLine, New XElement ("Comment", "TEST")))
'The above is halfway.
'&lt;Details&gt;
  '&lt;Food Expenses&gt;10000 Yen
  '&lt;Comments&gt;TEST&lt;/Comments&gt;&lt;/Food Expenses&gt;
'&lt;/Details&gt;
‘If above output&lt;Food Expenses&gt;10000 Yen (with line break)&lt;Comment&gt;TEST&lt;/Comment&gt;(No line break)&lt;/Food Expense&gt;
Supplemental information (FW/tool version etc.)

.net4.5
C #

  • Answer # 1

    XML represents the structure of the data.
    The format is designed to be read by humans, but its essence is to process data mechanically.

    This question tries to format the XML itself, not the structure of the data.
    In this case, I think that it is better to insert a new line after converting it to a character string.

    var xml = new XElement ("Details", new XElement ("Food Expenses", "10000 Yen", new XElement ("Comment", "TEST"))));
    Console.WriteLine (Regex.Replace (xml.ToString (SaveOptions.DisableFormatting), "(?<=>)", "\ n"));

  • Answer # 2

    xml = new XElement ("Details", new XElement ("Food Expense", "10000 yen" + Environment.NewLine, new XElement ("Comment", "TEST"), Environment.NewLine));


    Like this?