如何添加xml命名空间

时间:2009-05-29 20:58:43

标签: c# xml api namespaces

这个Feed(它的snippit)需要看起来像这样:

<AmazonEnvelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
                xsi:noNamespaceSchemaLocation="amzn-envelope.xsd">

我将如何添加到此C#代码中以添加额外的xmlns,xsi junk:

writer.WriteStartDocument();
writer.WriteStartElement("AmazonEnvelope");

此Feed在没有它的情况下被拒绝 -

2 个答案:

答案 0 :(得分:8)

试试这个:

writer.WriteStartElement("AmazonEnvelope");
writer.WriteAttributeString(
  "xmlns", "xsi", null, "http://www.w3.org/2001/XMLSchema-instance");
writer.WriteAttributeString(
  "xsi", "noNamespaceSchemaLocation", null, "amzn-envelope.xsd");
...
writer.WriteEndElement();

答案 1 :(得分:5)

.NET 3.5是一个选项吗?

XNamespace ns = "http://www.w3.org/2001/XMLSchema-instance";

string s = new XElement("AmazonEnvelope",
    new XAttribute(XNamespace.Xmlns + "xsi", ns),
    new XAttribute(ns + "noNamespaceSchemaLocation", "amzn-envelope.xsd")
).ToString();

XmlWriter

const string ns = "http://www.w3.org/2001/XMLSchema-instance";
writer.WriteStartDocument();
writer.WriteStartElement("AmazonEnvelope");
writer.WriteAttributeString("xmlns", "xsi", "", ns);
writer.WriteAttributeString("xsi", "noNamespaceSchemaLocation",
      ns, "mzn-envelope.xsd");
writer.WriteEndDocument();