上的XElement如何设置命名空间属性 [英] How do I set namespace attributes on an XElement

查看:1258
本文介绍了上的XElement如何设置命名空间属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将以下属性添加到的XElement:

I need to add the following attributes to an 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不会因为工作的:我敢肯定,是不是反正正确的方式。我怎么就没有添加这些?

Adding them as an XAttribute doesn't work because of the ":" and I'm sure is not the right way anyways. How do I add these on there?

推荐答案

用了淘<一href="http://www.falconwebtech.com/post/2010/06/03/Adding-schemaLocation-attribute-to-XElement-in-LINQ-to-XML.aspx">a很多博客的,但我终于想出了什么,我认为是正确的方式做到这一点:

It took scouring a lot of blogs but I finally came up with what I think is the "right" way to do this:

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

这篇关于上的XElement如何设置命名空间属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆