是否可以在C#代码文件中添加文字XML数据?我目前正在使用多行字符串文字,但你可以看到它变得混乱.有没有更好的方法呢?
string XML = @"<?xml version=""1.0"" encoding=""utf-8""?>
<customUI xmlns=""http://schemas.example.com/customui"">
<toolbar id=""save"">
</toolbar>
</customUI>";
Run Code Online (Sandbox Code Playgroud)
Mar*_*ell 17
如果XML足够大,可以考虑使用平坦的.xml文件,可以从磁盘加载,也可以作为资源嵌入.只要你只加载一次(可能在静态构造函数中),这对性能没有任何影响.它将更容易维护,因为它将使用IDE的XML文件编辑器.它不会妨碍你的代码.
Abb*_*bas 12
参考我的评论,我不记得我在哪里看到这个,但我终于找到了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
Run Code Online (Sandbox Code Playgroud)
作为一种特殊的,特定于案例的解决方案,如果您碰巧使用Razor引擎在ASP.NET环境中工作,则可以在CSHTML文件中:
Func<MyType, HelperResult> xml = @<root>
<item>@(item.PropertyA)</item>
<item>@(item.PropertyB)</item>
<item>@(item.PropertyC)</item>
</root>;
Run Code Online (Sandbox Code Playgroud)
添加了扩展方法:
public static XDocument ToXDocument<T>(this Func<T, HelperResult> source, T item)
{
return XDocument.Parse(source(item).ToHtmlString());
}
Run Code Online (Sandbox Code Playgroud)
然后你可以:
XDocument document = xml.ToXDocument(new MyType() {
PropertyA = "foo",
PropertyB = "bar",
PropertyC = "qux",
});
Run Code Online (Sandbox Code Playgroud)
又一次,特别的?是的.案件的具体情况?是的.但它有效,并提供了很好的智能感知.(请注意,它还会提供一堆有效性警告,具体取决于文档验证版本)
归档时间: |
|
查看次数: |
16022 次 |
最近记录: |