在C#中使用XML文本?

35

是否可以在C#代码文件中添加XML数据?我目前正在使用多行字符串文字,但这很凌乱。有更好的方法吗?

string XML = @"<?xml version=""1.0"" encoding=""utf-8""?>
<customUI xmlns=""http://schemas.example.com/customui"">
    <toolbar id=""save"">
    </toolbar>
</customUI>";
5个回答

38

XML文字是VB.NET的一个功能,不是C#。

你所发的内容在C#中已经尽可能接近了。

但你可能需要考虑将嵌入的双引号替换为单引号(因为两种类型都是有效的XML)。

对于较大的XML量,您可能需要考虑使用Marc提供的答案-使用XML文件(加载一次并存储在内存中),以便您可以利用XML编辑器。


12
作为一名掌握这两种语言的开发人员,这是我很少会想要使用 VB.NET 特性的时候之一。 :) 这个特性可以让我在 VB.NET 中编写 XML 更加简洁,比序列化更快。 - Dan Atkinson

18

如果XML文件太大影响阅读,请考虑使用一个扁平的.xml文件代替,可以从磁盘加载,也可以嵌入到资源中。只要在静态构造函数中加载一次,这对性能不会有任何影响。它将更容易维护,因为它将使用IDE的XML文件编辑器,并且不会干扰你的代码。


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

5
作为一种特殊且非常个案的解决方案,如果你恰好在使用Razor引擎的ASP.NET环境中工作,在一个CSHTML文件中,你可以:
```html @{ var myString = "This is my string"; } ```
这将允许你在CSHTML文件中创建和使用变量。
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。(请注意,它还将根据文档验证版本提供一堆有效性警告


我怀疑我不会在实践中使用这个,但这确实是一个非常有创意的方法。赞! - Jordan Gray

0

在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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接