C#XMLTextWriter包含默认的命名空间

时间:2015-02-09 10:28:46

标签: c# xml

如何使用XMLTextWriter

在XML中定义默认命名空间

我希望我的XML看起来像这样:

<myXml xmlns:nss="http://my/location/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://my/location/">

xmlTextWriter.WriteStartDocument();
xmlTextWriter.WriteStartElement("myXml");
xmlTextWriter.WriteAttributeString("xmlns", "nss", null, statusNamespace);
xmlTextWriter.WriteAttributeString("xmlns", "xsi", null, xsiSchemaNamespace);

如何在没有任何前缀的情况下获取xmlns默认值?

如果我另外添加以下行,我会得到the prefix cannot be redefined from to "http://my/location/"

xmlTextWriter.WriteAttributeString("xmlns", null, null, statusNamespace);

1 个答案:

答案 0 :(得分:0)

您通常应该优先使用直接接受命名空间的重载,而不是手动尝试通过属性应用命名空间。

此代码:

var myWriter = XmlTextWriter.Create("Blah1.xml");
myWriter.WriteStartDocument();
myWriter.WriteStartElement("myXml", "http://my/location/");
myWriter.WriteAttributeString("xmlns", "nss", null, "http://my/location/");
myWriter.WriteAttributeString("xmlns", "xsi", null,
         "http://www.w3.org/2001/XMLSchema-instance");
myWriter.Close();

生成:

<?xml version="1.0" encoding="utf-8"?>
<myXml xmlns:nss="http://my/location/" 
mlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://my/location/" />

(添加空格以提高可读性)