C# 如何创建具有特定命名空间的XElement?

C# 如何创建具有特定命名空间的XElement?,c#,.net,xml,linq-to-xml,C#,.net,Xml,Linq To Xml,我在LinqToXml中创建新元素时遇到问题。 这是我的代码: XNamespace xNam = "name"; XNamespace _schemaInstanceNamespace = @"http://www.w3.org/2001/XMLSchema-instance"; XElement orderElement = new XElement(xNam + "Example", new XAttribute(XNamespace.Xmlns +

我在LinqToXml中创建新元素时遇到问题。 这是我的代码:

XNamespace xNam = "name"; 
XNamespace _schemaInstanceNamespace = @"http://www.w3.org/2001/XMLSchema-instance";

XElement orderElement = new XElement(xNam + "Example",
                  new XAttribute(XNamespace.Xmlns + "xsi", _schemaInstanceNamespace));
我想得到这个:

<name:Example xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Example xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="name">

但在XML中,我总是得到以下信息:

<name:Example xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Example xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="name">

我做错了什么?

名称空间格式不正确,因为没有声明前缀
name
。因此,用XMLAPI构建它是不可能的。您可以做的是构造以下名称空间格式良好的XML


使用代码

//
XNamespace名称=”http://example.com/name";
XXi=”http://www.w3.org/2001/XMLSchema-instance";
XElement示例=新XElement(名称+“示例”,
新的XAttribute(XNamespace.Xmlns+“name”,name),
新的XAttribute(XNamespace.Xmlns+“xsi”,xsi));
Console.WriteLine(示例);

这就是你需要的V4Vendetta:这是类似的问题,但现在我得到了这个:
我忘了写这个了。命名空间名称在父节点中声明。创建xml之后,我总是在一些xml验证器上验证这一点。