如何设置默认XML命名空间的一个XDocument [英] How to set the default XML namespace for an XDocument
问题描述
如何设置现有的XDocument的默认命名空间(这样我就可以用DataContractSerializer的反序列化)。我试过如下:
How can I set the default namespace of an existing XDocument (so I can deserialize it with DataContractSerializer). I tried the following:
var doc = XDocument.Parse("<widget/>");
var attrib = new XAttribute("xmlns",
"http://schemas.datacontract.org/2004/07/Widgets");
doc.Root.Add(attrib);
我得到的例外是在的preFIX'相同的开始内'不能从重新定义'到'http://schemas.datacontract.org/2004/07/Widgets元素标记。
任何想法?
推荐答案
看来,LINQ到XML没有对这种用例提供了一个API(声明:我没有调查很深)。如果更改根元素的命名空间,如下所示:
It seems that Linq to XML does not provide an API for this use case (disclaimer: I didn't investigate very deep). If change the namespace of the root element, like this:
XNamespace xmlns = "http://schemas.datacontract.org/2004/07/Widgets";
doc.Root.Name = xmlns + doc.Root.Name.LocalName;
只有根元素将其命名空间的变化。所有的孩子都会有一个明确的空的xmlns标记。
Only the root element will have its namespace changed. All children will have an explicit empty xmlns tag.
一个解决办法是这样的:
A solution could be something like this:
public static void SetDefaultXmlNamespace(this XElement xelem, XNamespace xmlns)
{
if(xelem.Name.NamespaceName == string.Empty)
xelem.Name = xmlns + xelem.Name.LocalName;
foreach(var e in xelem.Elements())
e.SetDefaultXmlNamespace(xmlns);
}
// ...
doc.Root.SetDefaultXmlNamespace("http://schemas.datacontract.org/2004/07/Widgets");
或者,如果你preFER一个版本不发生变异,现有的文档:
Or, if you prefer a version that does not mutate the existing document:
public XElement WithDefaultXmlNamespace(this XElement xelem, XNamespace xmlns)
{
XName name;
if(xelem.Name.NamespaceName == string.Empty)
name = xmlns + xelem.Name.LocalName;
else
name = xelem.Name;
return new XElement(name,
from e in xelem.Elements()
select e.WithDefaultXmlNamespace(xmlns));
}
这篇关于如何设置默认XML命名空间的一个XDocument的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!