简体   繁体   English

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

[英]Should I generate XML as a string in C#?

When generating XML in C#, Is there a problem with generating it as a string? 在C#中生成XML时,将其生成为字符串是否存在问题? In the past I've found generating XML programatically very verbose and convoluted. 在过去,我发现以编程方式生成XML非常冗长和复杂。 Creating the xml through string concatenation/a string builder seems much easier but, it feels like bad practice. 通过字符串连接/字符串构建器创建xml似乎更容易,但感觉就像是不好的做法。
Should I generate XML as a string? 我应该将XML生成为字符串吗?

The XDocument, XElement and XAttribute classes make xml generation in C# much easier to do. XDocument,XElement和XAttribute类使得在C#中生成xml变得更容易。 Than using the XmlDocument or XmlWriter. 比使用XmlDocument或XmlWriter。

As an example, to produce this: 作为一个例子,产生这个:

<RootElement>
    <ChildElement Attribute1="Hello" Attribute2="World" />
    <ChildElement Attribute1="Foo" Attribute2="Bar" />
</RootElement>

You can do this: 你可以这样做:

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

Have you tryed Linq to Xml? 你有没有尝试过Linq到Xml? it is not very verbose: 它不是很冗长:

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

Before you think about generating XML using string concatenation instead of a proper library, please go and read the XML specification . 在考虑使用字符串连接而不是正确的库生成XML之前,请先阅读XML规范 Pay particular attention to niceties such as charsets and character references. 特别注意字符集和字符引用等细节。

You can do it now. 你现在可以做到。 I'll wait. 我会等。

Now ask yourself - do you really want to have to ensure that your concatenated string is valid according to all those rules and write all the helper functions yourself, or do you want to use a well tested library where all that logic has been encapsulated for you? 现在问问自己 - 你真的想要确保你的串联字符串根据所有这些规则有效并自己编写所有帮助函数,或者你是否想要使用经过良好测试的库,其中所有逻辑都已封装给你?

Good. 好。

Glad that's sorted. 很高兴分类。

I would recomend the following approach in most instances when you are generating xml. 在生成xml时,我会在大多数情况下推荐以下方法。

  1. Create an XSD for your XML 为您的XML创建XSD
  2. Compile the XSD into an object 将XSD编译为对象
  3. Populate your object 填充您的对象
  4. De-serialize your object into xml 将对象反序列化为xml

Benifits to doing this over just creating xml using the XMLDocuments 1. It's well defined with an XSD. 使用XMLDocuments创建xml的好处是1.使用XSD很好地定义了它。 Other developers know what the xml they are receiving is (or what they are modifying) 2. Easy to change in the future. 其他开发人员知道他们接收的xml是什么(或者他们正在修改什么)2。将来很容易改变。 3. Far greater less chance of typo bugs in your xml document. 3. xml文档中拼写错误的可能性要小得多。

Let me know if you need any code examples or additional assistance in how this would be executed. 如果您需要任何代码示例或有关如何执行此操作的其他帮助,请与我们联系。

Note: We generate our cs files from xsds at build time to ensure someone does not manually modify the generated code. 注意:我们在构建时从xsds生成cs文件,以确保有人不会手动修改生成的代码。

Creating the XML through string concatenation is definitely bad practice. 通过字符串连接创建XML绝对是不好的做法。 The XmlDomDocument isn't very verbose or convoluted; XmlDomDocument不是很冗长或复杂; I've always found it to be pretty easy (and safe) to work with. 我总是发现它很容易(也很安全)。

No, you shouldn't. 不,你不应该。 The XML libraries in .NET (and other platforms) ensure that you create valid XML, and saves you a lot of time worrying about parsing it back in. Also, if someone else needs to use your XML, and complains it's incorrect, you can rule out the actual XML itself, and will save you a lot of time checking you are concatenating properly. .NET(和其他平台)中的XML库确保您创建有效的XML,并且可以节省大量时间来担心将其解析回来。另外,如果其他人需要使用您的XML,并且抱怨它不正确,您可以排除实际的XML本身,并且会为你节省大量的时间来检查你是否正确连接。

XmlWriter is not that bad when you're formatting your code correctly: 在正确格式化代码时,XmlWriter并没有那么糟糕:

StringBuilder builder = new StringBuilder();
using (XmlWriter writer = XmlWriter.Create(builder))
{
    writer.WriteStartDocument();

    writer.WriteStartElement("root");

    writer.WriteStartElement("Node1");
    writer.WriteAttributeString("att1", "value");
    writer.WriteEndElement();

    writer.WriteStartElement("Node2");
    writer.WriteString("inner text");
    writer.WriteEndElement();

    writer.WriteEndElement();

    writer.WriteEndDocument();
}

You could also add identation in your code to facilitate the comprehension. 您还可以在代码中添加标识以便于理解。

using (XmlWriter writer = XmlWriter.Create(builder))
{
    writer.WriteStartDocument();
    {
        writer.WriteStartElement("root");
        {
            writer.WriteStartElement("Node1");
            writer.WriteAttributeString("att1", "value");
            writer.WriteEndElement();

            writer.WriteStartElement("Node2");
            writer.WriteString("inner text");
            writer.WriteEndElement();
        }
        writer.WriteEndElement();
    }
    writer.WriteEndDocument();
}

Using an XmlTextWriter, you can drop the results into a StringBuilder and use the resulting string. 使用XmlTextWriter,您可以将结果放入StringBuilder并使用生成的字符串。 Also, using the XmlTextWriter, you can place the content into a stream. 此外,使用XmlTextWriter,您可以将内容放入流中。 So, if you're looking for flexibility, use an XmlTextWriter. 因此,如果您正在寻找灵活性,请使用XmlTextWriter。

If your question is about constructing an xml file by string concatenation, don't do that. 如果您的问题是关于通过字符串连接构建xml文件,请不要这样做。 Use a StringBuilder if you're going to put an xml document together without any other help. 如果您要将xml文档放在一起而没有任何其他帮助,请使用StringBuilder。

I would avoid manually creating the xml through "concatenation". 我会避免通过“连接”手动创建xml。 You increase the likelyhood of errors in the generated xml. 您增加了生成的xml中的错误可能性。 Microsoft's xml creation classes have been tested rather thoroughly. 微软的xml创建类已经过相当彻底的测试。 Use that to your advantage. 使用它对您有利。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM