是否可以在C#代码文件中添加XML数据?我目前正在使用多行字符串文字,但这很凌乱。有更好的方法吗?
string XML = @"<?xml version=""1.0"" encoding=""utf-8""?>
<customUI xmlns=""http://schemas.example.com/customui"">
<toolbar id=""save"">
</toolbar>
</customUI>";
XML文字是VB.NET的一个功能,不是C#。
你所发的内容在C#中已经尽可能接近了。
但你可能需要考虑将嵌入的双引号替换为单引号(因为两种类型都是有效的XML)。
对于较大的XML量,您可能需要考虑使用Marc提供的答案-使用XML文件(加载一次并存储在内存中),以便您可以利用XML编辑器。
如果XML文件太大影响阅读,请考虑使用一个扁平的.xml文件代替,可以从磁盘加载,也可以嵌入到资源中。只要在静态构造函数中加载一次,这对性能不会有任何影响。它将更容易维护,因为它将使用IDE的XML文件编辑器,并且不会干扰你的代码。
参考我的评论,我记不清在哪里看到这个了,但我最终找到了XmlBuilder链接。
回想起来,Linq to XML似乎是你最好的选择。它比连接XML字符串更加清晰、快速和易于维护:
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 (<?xml version="1.0" encoding="utf-16" standalone="yes"?>)
var xmlString = stringWriter.ToString(); //Save as string
doc.Save(@"d:\out.xml"); //Save to file
Func<MyType, HelperResult> xml = @<root>
<item>@(item.PropertyA)</item>
<item>@(item.PropertyB)</item>
<item>@(item.PropertyC)</item>
</root>;
通过添加扩展方法:
public static XDocument ToXDocument<T>(this Func<T, HelperResult> source, T item)
{
return XDocument.Parse(source(item).ToHtmlString());
}
XDocument document = xml.ToXDocument(new MyType() {
PropertyA = "foo",
PropertyB = "bar",
PropertyC = "qux",
});
再说一遍,这很奇怪吗?是的。与案例相关吗?是的。但它有效,并且提供了出色的Intellisense。(请注意,它还将根据文档验证版本提供一堆有效性警告)
在C#中,我们最接近的可能就是通过LINQ来实现,类似这样:
var xml = XDocument.Load(
new StringReader(@"<Books>
<Book author='Dan Brown'>The Da Vinci Code</Book>
<Book author='Dan Brown'>The Lost Symbol</Book>
</Books>"));
var query = from book in xml.Elements("Books").Elements("Book")
where book.Attribute("author").Value == "Dan Brown"
select book.Value;
foreach (var item in query) Console.WriteLine(item);