'XmlDocument.CreateElement();' 只创建一个元素吗?

Does 'XmlDocument.CreateElement();' ONLY create an element?

似乎 someXml.CreateElement("abc"); 只做一件事:创建元素。它没有像我预期的那样将它添加为子项,它似乎也没有做任何其他事情。

但这没有多大意义。为什么使用实例方法而不是静态方法创建元素?这将表明它 确实 与实例有某种关系。但我找不到任何东西,因此我的问题。

微软文档中的备注提到默认属性是在返回的对象上创建的。命名空间浮现在脑海中,因为它们可能会自动应用于基于 XmlDocument 的 schema/defaults.

的新元素

还说明必须手动添加到想要的父节点。

来自https://msdn.microsoft.com/en-us/library/fw1ys7w6(v=vs.110).aspx

Note that the instance returned implements the XmlElement interface, so default attributes would be created directly on the returned object.

Although this method creates the new object in the context of the document, it does not automatically add the new object to the document tree. To add the new object, you must explicitly call one of the node insert methods.

我认为该方法不会像您期望的那样自动将元素添加为子元素的原因是因为无法知道应该将元素添加到何处。该文档可以有很多子元素,并且没有指定应将创建的元素添加到哪个元素。它不能默认将它添加到根元素,因为很有可能并不总是会成为所需的位置。

如前所述,使用实例方法而不是静态方法的好处是可以在新创建的元素上自动创建默认属性(例如命名空间)。这样,一旦创建,只需将其添加到文档中的适当位置即可。