How to prevent blank xmlns attributes in output fr

2019-01-05 01:03发布

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.

7条回答
▲ chillily
2楼-- · 2019-01-05 02:01

If the <loner> element in your sample XML didn't have the xmlns default namespace declaration on it, then it would be in the whatever:name-space-1.0 namespace rather than being in no namespace. If that's what you want, you need to create the element in that namespace:

xml.CreateElement("loner", "whatever:name-space-1.0")

If you want the <loner> element to be in no namespace, then the XML that's been produced is exactly what you need, and you shouldn't worry about the xmlns attribute that's been added automatically for you.

查看更多
登录 后发表回答