无法在xml文档中设置属性

时间:2015-10-05 02:25:03

标签: c# xml

我正在尝试设置以下属性,但它们没有正确完成。

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

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

但它显示如下:

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

我的版本的noNamespaceSchemaLocation属性没有xsi。

编写xml的C#代码

        var xmldoc = new XmlDocument();
        var amazonEnvelope = xmldoc.CreateElement("AmazonEnvelope");
        amazonEnvelope.SetAttribute("xsi:noNamespaceSchemaLocation", "amzn-envelope.xsd");
        amazonEnvelope.SetAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
        xmldoc.AppendChild(amazonEnvelope);

1 个答案:

答案 0 :(得分:1)

如果您的.NET框架版本&gt; 3.0 或者您可以使用XDocument代替XmlDocument

命名空间

using System.Xml.Linq;

代码

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

XDocument doc = new XDocument(
                new XElement("AmazonEnvelope",
                    new XAttribute(XNamespace.Xmlns + "xsi", "http://www.w3.org/2001/XMLSchema-instance"),
                    new XAttribute(xsi + "noNamespaceSchemaLocation", "amzn-envelope.xsd")
                    )
                );
相关问题