如何使用XDocument创建具有多个名称空间的Xml

时间:2011-05-21 01:42:52

标签: c# .net xml linq-to-xml

我想创建一个包含多个命名空间的文档(请参阅下面的Xml)。我怎么能用XDocument做到这一点?我的最终结果如下:

<?xml version="1.0" encoding="utf-8"?>
<a:feed xmlns:a="http://www.w3.org/2005/Atom" xmlns:os="http://a9.com/-/spec/opensearch/1.1/" xmlns="http://schemas.zune.net/catalog/apps/2008/02">
  <a:link rel="prev" type="application/atom+xml" href="myUrl" />
  <a:link rel="next" type="application/atom+xml" href="myUrl" />
  <a:link rel="self" type="application/atom+xml" href="myUrl" />
  <a:updated>2008-05-20T22:50:46.7932864Z</a:updated>

这是我到目前为止的代码。

    XNamespace nsW3Atom = "http://www.w3.org/2005/Atom";
    XNamespace nsOs = "http://a9.com/-/spec/opensearch/1.1/";
    XNamespace nsZune = "http://schemas.zune.net/calatog/apps/2008/02";

    XDocument doc =
        new XDocument(
            // new XDeclaration("1.0", "utf-8", "no"),
            new XElement("feed",
                new XAttribute("a", nsW3Atom),
                new XAttribute("os", nsOs),
                new XAttribute("os2", nsZune),
                new XElement(XNamespace.Xmlns + "link", new XAttribute("rel", "prev"), new XAttribute("type", "application/atom+xml")),
                new XElement(XNamespace.Xmlns + "link", new XAttribute("rel", "next"), new XAttribute("type", "application/atom+xml")),
                new XElement(XNamespace.Xmlns + "link", new XAttribute("rel", "self"), new XAttribute("type", "application/atom+xml"))));

提前感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

 XNamespace a="http://www.w3.org/2005/Atom";
 XNamespace os = "http://a9.com/-/spec/opensearch/1.1/";
 XNamespace def = "http://schemas.zune.net/catalog/apps/2008/02";

 var doc =
     new XDocument(new XElement(a + "feed", 
                         new XAttribute(XNamespace.Xmlns + "a", a),
                         new XAttribute(XNamespace.Xmlns + "os", os),
                         new XAttribute("xmlns", def)));

然后,如果您想使用命名空间,请在任何元素前加上+

答案 1 :(得分:0)

创建属性时,请使用xmlns:前缀。

            new XAttribute("xmlns:a", nsW3Atom),
            new XAttribute("xmlns:os", nsOs),
            new XAttribute("xmlns:os2", nsZune)