【问题标题】:How to assign xml content to a string explicitly如何将 xml 内容显式分配给字符串
【发布时间】:2013-07-13 02:47:00
【问题描述】:

你知道我如何明确地将 xml 内容分配给字符串吗? 示例:

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>
"

我想这样做,但文件要大得多。我需要它是因为我想在我的单元测试中使用它,但是当我尝试在引号之间粘贴内容时它会显示很多错误。

【问题讨论】:

    标签: c# xml parsing assign


    【解决方案1】:

    你需要verbatim string literal(以@符号开头的字符串)和转义引号(即使用双""而不是单"):

            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>
    ";
    

    【讨论】:

      【解决方案2】:

      用途:

      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>
          ";
      

      或者只是将 XML 存储在一个文件中,然后在运行时使用 File.ReadAllText() 将其加载到变量中:

      string myXml = File.ReadAllText("test.xml");
      

      【讨论】:

      • 我一直在考虑文件存储的选项。我想知道将 xml 文件保存在我的解决方案中是否是一种不好的做法?我想知道将它存储在某个地方以便我可以阅读正确的方式。
      • 我相信在你的代码中存储 XML 是你所有选项中最不好的实践:)
      猜你喜欢
      • 2015-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-15
      • 2014-01-05
      • 2014-04-19
      • 2021-04-23
      相关资源
      最近更新 更多