如何prevent空白的xmlns从.net的XmlDocument的输出属性? [英] How to prevent blank xmlns attributes in output from .NET's XmlDocument?

查看:185
本文介绍了如何prevent空白的xmlns从.net的XmlDocument的输出属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当从XmlDocument的.NET中生成XML,空白的xmlns 属性出现第一次一个元素的没有的关联的命名空间插入;怎么会这样prevented?

When generating XML from XmlDocument in .NET, a blank xmlns attribute appears the first time an element without an associated namespace is inserted; how can this be prevented?

例如:

XmlDocument xml = new XmlDocument();
xml.AppendChild(xml.CreateElement("root",
    "whatever:name-space-1.0"));
xml.DocumentElement.AppendChild(xml.CreateElement("loner"));
Console.WriteLine(xml.OuterXml);

输出:

<root xmlns="whatever:name-space-1.0"><loner xmlns="" /></root>

希望的输出:

<root xmlns="whatever:name-space-1.0"><loner /></root>

是否有适用于的XmlDocument code的解决方案,而不是发生什么的的文件转换为字符串 OuterXml

Is there a solution applicable to the XmlDocument code, not something that occurs after converting the document to a string with OuterXml?

我的理由这样做是为了看看我是否能满足使用的XmlDocument生成的XML特定协议的标准XML。空白的xmlns 属性的可以的没有折断或混淆解析器,但它也不是present的任何使用,我已经看到了这协议。

My reasoning for doing this is to see if I can match the standard XML of a particular protocol using XmlDocument-generated XML. The blank xmlns attribute may not break or confuse a parser, but it's also not present in any usage that I've seen of this protocol.

推荐答案

由于杰里米·Lew的答案,多一点玩耍,我想通了,如何删除空白的xmlns 属性:创建任何你想要的子节点时,通过在根节点的命名空间的没有的有一个preFIX。使用未经preFIX在根命名空间意味着你需要使用的子元素相同的命名空间为他们的的没有prefixes。

Thanks to Jeremy Lew's answer and a bit more playing around, I figured out how to remove blank xmlns attributes: pass in the root node's namespace when creating any child node you want not to have a prefix on. Using a namespace without a prefix at the root means that you need to use that same namespace on child elements for them to also not have prefixes.

固定code:

XmlDocument xml = new XmlDocument();
xml.AppendChild(xml.CreateElement("root", "whatever:name-space-1.0"));
xml.DocumentElement.AppendChild(xml.CreateElement("loner", "whatever:name-space-1.0")); 
Console.WriteLine(xml.OuterXml);

谢谢大家给你的答案害得我在正确的方向!

Thanks everyone to all your answers which led me in the right direction!

这篇关于如何prevent空白的xmlns从.net的XmlDocument的输出属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆