如何创建 xmlns:xsi 但没有前缀的根节点?

How to create root node with xmlns:xsi but no prefix?

创建没有前缀但显示xmlns:xsi="blah"的根节点的正确方法是什么?基本上我想要这样的东西:

<EDSCrate xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="EDS_Crate_2010-02-10.xsd" version="0.95">
    <Whatever>
    </Whatever>
</EDSCrate>

然而,我已经尝试了很多方法,它就是不会给我一个没有命名空间的简单节点,即使有,它也没有在属性中给我正确的 xmlns:xsi .

我想避免任何黑客攻击,例如覆盖 ToString 和自己替换 XmlWriter 中的文本。

string uri = "http://www.w3.org/2001/XMLSchema-instance";

XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = true;
doc.AppendChild(doc.CreateXmlDeclaration("1.0", "UTF-8", null));

nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("xsi", uri);

XmlElement root = doc.CreateElement("EDSCrate", uri);
// at this point, it already added xmlns="http://www.w3.org/2001/XMLSchema-instance" without me doing anything
root.RemoveAllAttributes();
// but i want xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"!!
root.SetAttribute("xmlns:xsi", uri);
root.SetAttribute("xsi:noNamespaceSchemaLocation", "EDS_Crate_2010-02-10.xsd");

我发现使用 Linq2Xml 更容易。

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

var xdoc = new XDocument(
                new XElement(
                    "EDSCrate",
                    new XAttribute(XNamespace.Xmlns + "xsi", xsi),
                    new XAttribute(xsi + "noNamespaceSchemaLocation", "EDS_Crate_2010-02-10.xsd"),
                    new XAttribute("version", "0.95"),
                    new XElement("Whatever","")
                )
            );
var xml = xdoc.ToString();

输出:

<EDSCrate xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
          xsi:noNamespaceSchemaLocation="EDS_Crate_2010-02-10.xsd" 
          version="0.95">
  <Whatever></Whatever>
</EDSCrate>
string uri = "http://www.w3.org/2001/XMLSchema-instance";

var doc = new XmlDocument();
doc.AppendChild(doc.CreateXmlDeclaration("1.0", "UTF-8", null));

var root = doc.CreateElement("EDSCrate");
doc.AppendChild(root);
root.AppendChild(doc.CreateElement("Whatever"));

var attr = doc.CreateAttribute("xsi", "noNamespaceSchemaLocation", uri);
attr.InnerText = "EDS_Crate_2010-02-10.xsd";
root.SetAttributeNode(attr);

root.SetAttribute("version", "0.95");