【问题标题】:How to create an Xml with multiple namescapes using XDocument如何使用 XDocument 创建具有多个名称的 Xml
【发布时间】:2011-05-21 01:42:52
【问题描述】:

我想创建一个具有多个名称空间的文档(请参阅下面的 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"))));

提前感谢您的帮助!

【问题讨论】:

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


    【解决方案1】:
     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)));
    

    那么如果你想使用 a 命名空间,在任何元素前面加上 a+

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      猜你喜欢
      • 2012-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-13
      相关资源
      最近更新 更多