Use XML Literals in C#?

后端 未结 5 1888
遇见更好的自我
遇见更好的自我 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:27

    With reference to my comment, I couldn't recall where I saw this, but I finally found the XmlBuilder link.

    In retrospect, it seems Linq to XML would be your best bet. It's cleaner, faster and more maintainable than concatenating XML strings:

    XNamespace ns = "http://schemas.example.com/customui";
    XDocument doc = new XDocument(
                        new XDeclaration("1.0", "utf-8", "yes"),
                        new XElement(ns + "customUI",
                            new XElement(ns + "taskbar",
                                new XAttribute("id", "save"))
                        )
                    );
    
    var stringWriter = new StringWriter();
    doc.Save(stringWriter); //Write to StringWriter, preserving the declaration ()
    var xmlString = stringWriter.ToString(); //Save as string
    doc.Save(@"d:\out.xml"); //Save to file
    

提交回复
热议问题