对属性的XElement默认命名空间提供了意想不到的行为
-
22-07-2019 - |
题
我无法创建包含默认命名空间和指定名称空间的XML文档,很难解释容易只是展示一下我试图产生...
<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")),
new XElement(aw + "Book",
new XAttribute(aw + "title", "I Robot"),
new XAttribute(aw + "author", "Isaac Asimov")));
基于在MSDN一个例如
**** **** EDIT
好了,对XML命名空间是如何工作的一些实验我现在很迷茫......
如果我删除了AW + theattribute我得到了我后...但现在看来,我是后实际上不是我所期待的。我认为,命名空间是从父母那里继承,这是不是属性也是如此?因为,该代码读取属性如我所料不工作...
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 +的属性其确定,导致我认为我不能在默认的命名空间属性。这是正确的吗?
解决方案
好问题。我挖了一下周围,发现该位XML规范的 :
一个默认命名空间声明 适用于所有前缀的元素 在其范围内的名字。默认 命名空间声明不适用 直接把属性名;该 的前缀的解释 属性是由确定 元件上它们出现。
它以后前进到举这个例子:
例如,每个坏空元素标签的是在下面的非法:
<!-- 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>
然而,每个下面的是合法的,第二因为默认名称空间不>适用于属性名:
<!-- 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>
所以基本上,它看起来像属性名没有得到默认的命名空间,这说明你已经看到的一切:)
其他提示
XElement doc = XElement.Parse(ToXml());
doc.DescendantsAndSelf().Attributes().Where(a => a.IsNamespaceDeclaration).Remove();
var ele = doc.DescendantsAndSelf();
foreach (var el in ele)
el.Name = ns != null ? ns + el.Name.LocalName : el.Name.LocalName;
有关谁比谁了2天试图寻找一个答案。
不隶属于 StackOverflow