在XmlWriter中添加多个命名空间声明

29

我正在尝试使用XmlWriter写出以下元素

<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2" xmlns:kml="http://www.opengis.net/kml/2.2" xmlns:atom="http://www.w3.org/2005/Atom">

我已经完成了使用以下语句的第一次声明:

writer.WriteStartElement("kml", "http://www.opengis.net/kml/2.2");

我该如何将剩余的三个声明添加到同一个元素中?

3个回答

51
writer.WriteAttributeString("xmlns","gx", null, "http://www.google.com/kml/ext/2.2");
writer.WriteAttributeString("xmlns","kml", null, "http://www.opengis.net/kml/2.2");
writer.WriteAttributeString("xmlns","atom", null, "http://www.w3.org/2005/Atom");

这是从https://msdn.microsoft.com/en-us/library/cfche0ka(v=vs.100).aspx获取的。


10
Ryan B的回答不完整,因为XML命名空间只被写为属性,而没有在名称表中注册,所以LookupPrefix将无法获取一个XML命名空间的前缀,例如http://www.w3.org/2005/Atom。它将返回null而不是atom
要编写一个命名空间属性并注册命名空间,请使用:
writer.WriteAttributeString("atom",
                            "http://www.w3.org/2000/xmlns/",
                            "http://www.w3.org/2005/Atom");

使用命名空间http://www.w3.org/2000/xmlns/还会在名称表中注册前缀。


值得注意的是这里没有明确说明的一点:包括xmlns命名空间的URI会产生副作用,将"xmlns"写入属性中,因此之前代码中看到的前导参数是不需要的。 - Maury Markowitz

0
命名空间只是属性。使用标准的元素属性书写方式即可。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接