Use XML Literals in C#?

后端 未结 5 1875
遇见更好的自我
遇见更好的自我 2020-12-05 23:16

Is it possible to add literal XML data within a C# code file? I\'m currently using a multiline string literal but it gets messy as you can see. Any better way of doing this?

5条回答
  •  抹茶落季
    2020-12-05 23:45

    As a peculiar, and very case-specific solution, if you happen to be working in an ASP.NET environment using the Razor engine, in a CSHTML file you can:

    Func xml = @
        @(item.PropertyA)
        @(item.PropertyB)
        @(item.PropertyC)
    ;
    

    With the addition of an extension method:

    public static XDocument ToXDocument(this Func source, T item)
    {
        return XDocument.Parse(source(item).ToHtmlString());
    }
    

    You can then:

    XDocument document = xml.ToXDocument(new MyType() {
        PropertyA = "foo",
        PropertyB = "bar",
        PropertyC = "qux",
    });
    

    Again, peculiar? Yes. Case-specific? Yes. But it works, and gives great Intellisense. (mind you, it also will give a bunch of validity warnings, depending on the document validation version)

提交回复
热议问题