10

Do you know how I can explicitlyt assign xml content to a string ? Example :

string myXml = "
<?xml version="1.0"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
"

I want to do this but with a quite bigger file.I need it because I want to use it in my Unit testing but it shows lots of errors when I am trying to paste the content between the quotes.

mathinvalidnik
  • 1,566
  • 10
  • 35
  • 57

3 Answers3

20

You need to verbatim string literal (string which starts with @ symbol) with escaped quotes (i.e. use double "" instead of single "):

        string myXml = @"
<?xml version=""1.0""?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
";
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
4

Use:

string myXml = @"
    <?xml version=""1.0""?>
    <note>
    <to>Tove</to>
    <from>Jani</from>
    <heading>Reminder</heading>
    <body>Don't forget me this weekend!</body>
    </note>
    ";

Or just store the XML in a file and load it into the variable at runtime using File.ReadAllText():

string myXml = File.ReadAllText("test.xml");
Alex Filipovici
  • 31,789
  • 6
  • 54
  • 78
  • I've been thinking about that option with the file storing.I was wondering if it is a bad practice to keep xml files in my solution?I was wondering of storing it there somewhere so I can read it right the way. – mathinvalidnik Jul 15 '13 at 10:04
  • 1
    I believe that storing XML in your code is the _least good_ practice from all the options you have :) – Alex Filipovici Jul 15 '13 at 10:05
  • Why is it a bad practice? It is faster to keep it in a variable. I have to potentially read from the file 20 times in a second. Reading from the file is faster. – pianocomposer Jun 23 '22 at 22:57
0

Beginning with C# 11, you can use raw string literals to more easily create strings that are multi-line by using 3 or more double quotes to wrap your string.

For eg:

string myXml = """
    <?xml version="1.0"?>
    <note>
        <to>Tove</to>
        <from>Jani</from>
        <heading>Reminder</heading>
        <body>Don't forget me this weekend!</body>
    </note>
    """;

Reference: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/strings/#raw-string-literals

Ash K
  • 1,802
  • 17
  • 44