且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何设置默认XML命名空间的一个XDocument

更新时间:2023-11-24 16:38:46

看来,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));
}