我应该在C#中将XML生成为字符串吗?

mac*_*ojw 11 c# xml string

在C#中生成XML时,将其生成为字符串是否存在问题?在过去,我发现以编程方式生成XML非常冗长和复杂.通过字符串连接/字符串构建器创建xml似乎更容易,但感觉就像是不好的做法.
我应该将XML生成为字符串吗?

Rob*_*Day 13

XDocument,XElement和XAttribute类使得在C#中生成xml更容易.比使用XmlDocument或XmlWriter.

作为一个例子,产生这个:

<RootElement>
    <ChildElement Attribute1="Hello" Attribute2="World" />
    <ChildElement Attribute1="Foo" Attribute2="Bar" />
</RootElement>
Run Code Online (Sandbox Code Playgroud)

你可以这样做:

XDocument xDocument = new XDocument(
    new XElement("RootElement",
        new XElement("ChildElement",
            new XAttribute("Attribute1", "Hello"),
            new XAttribute("Attribute2", "World")
        ),
        new XElement("ChildElement",
            new XAttribute("Attribute1", "Foo"),
            new XAttribute("Attribute2", "Bar")
        )
    )
);
Run Code Online (Sandbox Code Playgroud)


Gre*_*ire 7

你有没有尝试过Linq到Xml?它不是很冗长:

XElement xml = new XElement("contacts",
                    new XElement("contact", 
                        new XAttribute("id", "1"),
                        new XElement("firstName", "first"),
                        new XElement("lastName", "last")
                    ),
                    new XElement("contact", 
                        new XAttribute("id", "2"),
                        new XElement("firstName", "first2"),
                        new XElement("lastName", "last2")
                    )
                );
Console.Write(xml);
Run Code Online (Sandbox Code Playgroud)


Gre*_*ech 5

在考虑使用字符串连接而不是正确的库生成XML之前,请先阅读XML规范.特别注意字符集和字符引用等细节.

你现在可以做到.我会等.

现在问问自己 - 你真的想要确保你的串联字符串根据所有这些规则有效并自己编写所有帮助函数,或者你是否想要使用经过良好测试的库,其中所有逻辑都已封装给你?

好.

很高兴分类.