Skip to main content
 首页 » 编程设计

c#之如何使用命名空间创建 XElement

2024年02月13日14rubylouvre

我需要生成这样的 xml:

<urlset xmlns:video="http://www.google.com/schemas/sitemap-video/1.1"  xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> 
<url> 
   <loc>http://blabla</loc> 
   <video:video> 
     <video:player allow_embed="yes">http://blablabla</video:player_loc>       
   </video:video> 
</url> 

我想不出使用 namespace 的方法。我什至无法正确创建 urlset 元素,我正在尝试:

 XNamespace _defaultNamespace = "http://www.sitemaps.org/schemas/sitemap/0.9"; 
 XNamespace _videoNameSpace = "http://www.google.com/schemas/sitemap-video/1.1"; 
 
 new XElement("urlset",new XAttribute(_defaultNamespace+"video",_defaultNamespace)) 

它生成:

<?xml version="1.0" encoding="utf-8" standalone="yes"?> 
<urlset p1:video="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:p1="http://www.sitemaps.org/schemas/sitemap/0.9"> 

p1 是什么东西?

请您参考如下方法:

命名空间属性在 xmlns 命名空间中,所以你应该使用 XNamespace.Xmlns + attributeName 用于声明命名空间:

XNamespace ns = "http://www.sitemaps.org/schemas/sitemap/0.9"; 
XNamespace video = "http://www.google.com/schemas/sitemap-video/1.1"; 
var urlset = new XElement(ns + "urlset",                 
    new XAttribute(XNamespace.Xmlns + "video", video)); 

生产

<urlset xmlns:video="http://www.google.com/schemas/sitemap-video/1.1"  
        xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" /> 

完整的 xml 生成如下所示:

var urlset = new XElement(ns + "urlset",                 
    new XAttribute(XNamespace.Xmlns + "video", video), 
    new XElement(ns + "url", 
        new XElement(ns + "loc", "http:/blabla"), 
        new XElement(video + "video", 
            new XElement(video + "player", 
                new XAttribute("allow_embed", "yes"), 
                "http:/blabla"))));