<Root xmlns="http://www.adventure-works.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:SchemaLocation="http://www.someLocatation.Com/MySchemaDoc.xsd"> <Book title="Enders Game" author="Orson Scott Card" /> <Book title="I Robot" author="Isaac Asimov" /></Root>
但我最终得到的是……
<Root xmlns="http://www.adventure-works.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:SchemaLocation="http://www.someLocatation.Com/MySchemaDoc.xsd"> <Book p3:title="Enders Game" p3:author="Orson Scott Card" xmlns:p3="http://www.adventure-works.com" /> <Book p3:title="I Robot" p3:author="Isaac Asimov" xmlns:p3="http://www.adventure-works.com" /></Root>
我编写的用于生成此XML代码段的代码是……
Xnamespace aw = "http://www.adventure-works.com"; Xnamespace xsi = "http://www.w3.org/2001/XMLSchema-instance"; XElement root = new XElement(aw + "Root",new XAttribute("xmlns","http://www.adventure-works.com"),new XAttribute(Xnamespace.Xmlns + "xsi","http://www.w3.org/2001/XMLSchema-instance"),new XAttribute(xsi + "SchemaLocation","http://www.someLocatation.Com/MySchemaDoc.xsd"),new XElement(aw + "Book",new XAttribute(aw + "Title","Enders Game"),new XAttribute(aw + "author","Orson Scott Card")),"I Robot"),"Isaac Asimov")));
基于example on MSDN
****编辑****
好的,通过一些更多的实验,我现在对XML名称空间如何工作非常困惑….
如果我删除了aw属性我得到了我以后的东西……但现在看来我所追求的并不是我所期望的.我认为名称空间是从父母那里继承而来的,属性也不是这样吗?因为,这个读取属性的代码不能像我预期的那样工作……
XElement xe = XElement.Parse(textBox1.Text); Xnamespace aw = "http://www.adventure-works.com"; var qry = from x in xe.Descendants(aw + "Book") select (string)x.Attribute(aw + "author");
但是,如果我删除属性上的aw就可以了,这导致我假设我在默认命名空间中没有属性.它是否正确?
解决方法 好问题.我挖了一下,找到了 this bit of the XML spec:A default namespace declaration
applIEs to all unprefixed element
names within its scope. Default
namespace declarations do not apply
directly to attribute names; the
interpretation of unprefixed
attributes is determined by the
element on which they appear.
它后来继续给出这个例子:
For example,each of the bad empty-element Tags is illegal in the following:
<!-- http://www.w3.org is bound to n1 and n2 --><x xmlns:n1="http://www.w3.org" xmlns:n2="http://www.w3.org" > <bad a="1" a="2" /> <bad n1:a="1" n2:a="2" /></x>
However,each of the following is legal,the second because the default namespace does not > apply to attribute names:
<!-- http://www.w3.org is bound to n1 and is the default --><x xmlns:n1="http://www.w3.org" xmlns="http://www.w3.org" > <good a="1" b="2" /> <good a="1" n1:a="2" /></x>
所以基本上,默认情况下属性名称看起来没有命名空间,这解释了你所看到的一切:)
总结以上是内存溢出为你收集整理的c# – 属性上的XElement默认命名空间提供了意外行为全部内容,希望文章能够帮你解决c# – 属性上的XElement默认命名空间提供了意外行为所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)