xml 命名空间和 xml 文字
我正在 vb.net 中尝试 xml 文字,但有些东西我不明白。这是一个说明问题的小样本。我正在向空的 Visual Studio 项目添加两个 PropertyGroup
节点。第一个作为 xml 文字添加,第二个作为 new XElement
添加:
Imports <xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
Module MyModule
Sub Main()
Dim vbproj = <?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
</Project>
vbproj.Root.Add(<PropertyGroup></PropertyGroup>)
Dim xNameSpace As XNamespace = "http://schemas.microsoft.com/developer/msbuild/2003"
vbproj.Root.Add(New XElement(xNameSpace + "PropertyGroup"))
Console.WriteLine(vbproj)
End Module
此代码写入以下输出:
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup xmlns="http://schemas.microsoft.com/developer/msbuild/2003"></PropertyGroup>
<PropertyGroup />
</Project>
如您所见,第一个 PropertyGroup
节点包含冗余的 xmlns 声明。为什么会这样,可以避免吗?
I'm experimenting with xml literals in vb.net and there's something I don't get. Here's a small sample that illustrates the problem. I'm adding two PropertyGroup
nodes to an empty Visual Studio project. The first one is added as xml literal, the second as new XElement
:
Imports <xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
Module MyModule
Sub Main()
Dim vbproj = <?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
</Project>
vbproj.Root.Add(<PropertyGroup></PropertyGroup>)
Dim xNameSpace As XNamespace = "http://schemas.microsoft.com/developer/msbuild/2003"
vbproj.Root.Add(New XElement(xNameSpace + "PropertyGroup"))
Console.WriteLine(vbproj)
End Module
This code writes the following output:
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup xmlns="http://schemas.microsoft.com/developer/msbuild/2003"></PropertyGroup>
<PropertyGroup />
</Project>
As you can see, the first PropertyGroup
node contains a redundant xmlns declaration. Why is that, and can it be avoided?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这似乎是设计使然,基于阅读 导入声明(XML 命名空间)的 MSDN 页面)。
避免这种情况的最简单方法是使用
SaveOptions.OmitDuplicateNamespaces
枚举,在 .NET 4.0 中可用:如果 .NET 4.0 不是一个选项,那么您可能会考虑清理命名空间,如这两篇博客文章中所示:
XElement
上使用的扩展方法来删除命名空间。True
来从子项中删除命名空间。This appears to be by design, based on reading the MSDN page for Imports Statement (XML Namespace).
The simplest way to avoid it is by using the
SaveOptions.OmitDuplicateNamespaces
enumeration, which is available in .NET 4.0:If .NET 4.0 isn't an option then you might consider cleaning up the namespaces as shown in these two blog posts:
XElement
to remove the namespace.True
for the second parameter.