【问题标题】:How do I set namespace attributes on an XElement如何在 XElement 上设置命名空间属性
【发布时间】:2012-06-13 19:24:15
【问题描述】:

我需要将以下属性添加到 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 不起作用,而且我确信这不是正确的方法。如何在其中添加这些内容?

【问题讨论】:

    标签: .net xml linq-to-xml


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      我想你想要的在这里描述: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>
      

      【讨论】:

      • 这只是问题的一部分。请参阅下面的答案,了解我最终是如何做到的。
      猜你喜欢
      • 1970-01-01
      • 2014-12-31
      • 2012-08-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-26
      • 1970-01-01
      • 2012-05-29
      • 1970-01-01
      相关资源
      最近更新 更多