无法在xml文档中设置属性

本文关键字:设置 属性 文档 xml | 更新日期: 2023-09-27 18:16:11

我试图设置以下属性,但它们不能正确通过。

我希望我的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);

无法在xml文档中设置属性

如果你的。net框架版本是> 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")
                    )
                );