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

时间:2012-06-13 19:24:15

标签: .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">

将它们添加为XAttribute不起作用,因为“:”并且我确信不是正确的方法。如何在那里添加这些?

2 个答案:

答案 0 :(得分:18)

这需要淘汰a lot of blogs但我终于想出了我认为这样做的“正确”方法:

        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")
            );

答案 1 :(得分:9)

我认为你想要的是这里描述的:How to: Create a Document with Namespaces (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);

会产生:

<Root xmlns="http://www.adventure-works.com">
  <Child>child content</Child>
</Root>