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

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

问题描述

在.NET 中从XmlDocument 生成XML 时,第一次插入一个没有 关联命名空间的元素时会出现一个空白的xmlns 属性;如何避免这种情况?

示例:

XmlDocument xml = new XmlDocument();xml.AppendChild(xml.CreateElement("root",无论:name-space-1.0"));xml.DocumentElement.AppendChild(xml.CreateElement("孤独者"));Console.WriteLine(xml.OuterXml);

输出:

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

期望输出:

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

是否有适用于 XmlDocument 代码的解决方案,而不是在 将文档转换为带有 OuterXml 的字符串之后发生的事情?

我这样做的原因是看看我是否可以使用 XmlDocument 生成的 XML 匹配特定协议的标准 XML.空白的 xmlns 属性可能不会破坏或混淆解析器,但它也没有出现在我见过的该协议的任何用法中.

解决方案

感谢 Jeremy Lew 的回答和更多的尝试,我想出了如何删除空白的 xmlns 属性:传入根在创建您希望具有前缀的任何子节点时,节点的命名空间.在根使用没有前缀的命名空间意味着您需要在子元素上使用相同的命名空间,以便它们没有前缀.

固定代码:

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

感谢大家的回答,让我朝着正确的方向前进!

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?

Example:

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

Output:

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

Desired Output:

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

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

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.

解决方案

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.

Fixed 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!

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

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