如何添加XML命名空间

6

需要将这个动态源(其中的片段)完全呈现如下所示:

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

我该在这段C#代码中添加什么来增加额外的xmlns、xsi垃圾:

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

没有it技术支持的情况下,此源被拒绝--


1
你没有提到你使用的编程语言。人们会认为你在使用C#,因为WriteStartDocument是XmlWriter的一个方法,但这并不是保证。 - Randolpho
在下面 XML 片段的正中间行中,它写着 "C#"。 - marc_s
2个回答

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

哇,我在这里学到了很多!!我现在已经进展了...亚马逊接受了这个数据源...API有点敏感!! - Scott Kramer

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

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