如何在XElement上设置名称空间属性

Geo*_*uer 16 .net xml linq-to-xml

我需要将以下属性添加到XElement:

<xmlns="http://www.mysite.com/myresource" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.mysite.com/myresource TheResource.xsd">
Run Code Online (Sandbox Code Playgroud)

将它们作为XAttribute添加不起作用因为":"而且我肯定不是正确的方法.我如何在那里添加这些?

Geo*_*uer 19

它花了很多博客,但我终于提出了我认为这样做的"正确"方法:

        XNamespace ns = @"http://www.myapp.com/resource";
        XNamespace xsi = @"http://www.w3.org/2001/XMLSchema-instance";

        var root = new XElement(ns + "root", 
            new XAttribute(XNamespace.Xmlns+"xsi", xsi.NamespaceName),
            new XAttribute(xsi + "schemaLocation", @"http://www.myapp/resource TheResource.xsd")
            );
Run Code Online (Sandbox Code Playgroud)


Pet*_*nks 9

我想你想要的是这里描述的:如何:使用命名空间创建一个文档(C#)(LINQ to XML)

举一个例子:

// Create an XML tree in a namespace.
XNamespace aw = "http://www.adventure-works.com";
XElement root = new XElement(aw + "Root",
    new XElement(aw + "Child", "child content")
);
Console.WriteLine(root);
Run Code Online (Sandbox Code Playgroud)

会产生:

<Root xmlns="http://www.adventure-works.com">
  <Child>child content</Child>
</Root>
Run Code Online (Sandbox Code Playgroud)