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

27

我需要将以下属性添加到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个回答

30

我花了很多时间查阅很多博客文章,但最终我找到了我认为是“正确”做法:

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

12
我觉得你想要的在这里描述了:如何使用命名空间创建文档 (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>

这只是问题的一部分。请看下面我的回答,了解我最终是如何处理它的。 - George Mauer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接