如何:控制命名空间前缀 (C#) (LINQ to XML) Visual Studio 2010 

本主题介绍在序列化 XML 树时如何控制命名空间前缀。

在很多情况下,不需要控制命名空间前缀。

例如,您可能正在操作 XSLT 样式表或 XAML 文档,其中包含引用特定命名空间前缀的嵌入式 XPath 表达式,在这种情况下,一定要使用这些特定前缀对文档进行序列化。

这是控制命名空间前缀的最常见的原因。

xsd 作为架构命名空间的前缀。

如果使用特定前缀声明命名空间,LINQ to XML 将在序列化时尝试接受此命名空间前缀。

该属性的值即是命名空间的 URI。

示例

 

fc 前缀。

 
XNamespace aw = "http://www.adventure-works.com";
XNamespace fc = "www.fourthcoffee.com";
XElement root = new XElement(aw + "Root",
    new XAttribute(XNamespace.Xmlns + "aw", "http://www.adventure-works.com"),
    new XAttribute(XNamespace.Xmlns + "fc", "www.fourthcoffee.com"),
    new XElement(fc + "Child",
        new XElement(aw + "DifferentChild", "other content")
    ),
    new XElement(aw + "Child2", "c2 content"),
    new XElement(fc + "Child3", "c3 content")
);
Console.WriteLine(root);

此示例产生以下输出:

 
<aw:Root xmlns:aw="http://www.adventure-works.com" xmlns:fc="www.fourthcoffee.com">
  <fc:Child>
    <aw:DifferentChild>other content</aw:DifferentChild>
  </fc:Child>
  <aw:Child2>c2 content</aw:Child2>
  <fc:Child3>c3 content</fc:Child3>
</aw:Root>