System.Xml.XmlException: „':' 字符,十六进制值 0x3A,不能包含在名称中。”

System.Xml.XmlException: „The ':' character, hexadecimal value 0x3A, cannot be included in a name.”

我想在我的 xml 中创建这样的东西:

<root>
  <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
  </xsd:schema>
</root>

我的代码现在看起来像这样:

XElement rootElement = new XElement("root");
XDeclaration xDeclaration = new XDeclaration("1.0", "utf-8", "true");
XElement xdsElement = new XElement("xsd:schema"); // Exception there!

我的例外:

System.Xml.XmlException: „The ':' character, hexadecimal value 0x3A, cannot be included in a name.”

如何避免这个异常,也许有某种短语生成器?

正如@juharr 在评论中所说,您需要先将其定义为 XNamespace,方法如下:

var ns_xsd = XNamespace.Get("http://www.w3.org/2001/XMLSchema");
var ns_msdata = XNamespace.Get("urn:schemas-microsoft-com:xml-msdata");

var root = new XElement("root", 
    new XElement(ns_xsd + "schema", 
        new XAttribute("id", "root"), 
        new XAttribute("xmlns", ""), 
        new XAttribute(XNamespace.Xmlns + "xsd", ns_xsd),
        new XAttribute(XNamespace.Xmlns + "msdata", ns_msdata),
        new XAttribute(ns_msdata + "IsDataSet", "true")));