XElement添加xmlns属性

14

我正在使用 Linq to XML 创建一个新的 XML 文件,其中一部分内容是从现有的 XML 文件中获取的。我使用以下代码来实现这个目标。

var v2 = new XDocument(
  new XDeclaration("1.0", "utf-16", ""),
  new XComment(string.Format("Converted from version 1. Date: {0}", DateTime.Now)),
  new XElement(ns + "keyem",
    new XAttribute(XNamespace.Xmlns + "xsd", xsd.NamespaceName),
    new XAttribute(XNamespace.Xmlns + "xsi", xsi.NamespaceName),
    new XAttribute(xsi + "schemaLocation", schemaLocation.NamespaceName),
    new XAttribute("version", "2"),
    new XAttribute("description", description),
    new XElement(ns + "layout",
      new XAttribute("type", type),
      new XAttribute("height", height),
      new XAttribute("width", width),
      settings.Root)       // XML from an existing file

问题在于它向现有文件的第一个元素添加了 xmlns = ""。

结果是:

<?xml version="1.0" encoding="utf-16"?>
<foo 
  xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://tempuri.org/KeyEmFileSchema.xsd KeyEmFileSchema.xsd"
  xmlns="http://tempuri.org/KeyEmFileSchema.xsd">
  <settings xmlns="">
      ...
  </settings>
</foo>

我正在读取的XML文件看起来像这样,但如果需要的话我可以更改它

<?xml version="1.0" encoding="utf-16"?>
<settings>
  <colormaps>
    <colormap color="Gray"     textcolor="Black"/>
    <colormap color="DarkGray" textcolor="White"/>
    <colormap color="Black"    textcolor="White"/>
    <colormap color="Cyan"     textcolor="Black"/>
  </colormaps>
  <macromaps>
    <macromap pattern="^@([0-9A-F]{2})\|([0-9A-F]{2})$"  replace="{ESC}$1{ESC}$2{MOUSERESET}"/>
    <macromap pattern="^\$([0-9A-F]{2})\|([0-9A-F]{2})$" replace="{USERCLICK}{ESC}$1{ESC}$2{MOUSERESET}"/>
    <macromap pattern="^\$([0-9A-F]{2})$"                replace="{USERCLICK}{ESC}$1"/>
  </macromaps>
  <keydefault color="Cyan"/>
  <groupdefault color="DarkGray"/>
</settings>
2个回答

15

您看到这个提示是因为设置元素(可能来自您的文档)不属于此命名空间。它属于默认/ null-uri 命名空间。

如果要更改命名空间,您需要转换输入文档。

这个简化的示例将您的 XML 文件放入另一个文档中,但在执行此操作之前,它会将该 XML 文件中的每个元素的命名空间更改为目标文档的命名空间...

    static void ProcessXmlFile()
    {
        XNamespace ns = "http://tempuri.org/KeyEmFileSchema.xsd/";

        // load the xml document
        XElement settings = XElement.Load("data.xml");

        // shift ALL elements in the settings document into the target namespace
        foreach (XElement e in settings.DescendantsAndSelf())
        {
            e.Name = ns + e.Name.LocalName;
        }

        // write the output document
        var file = new XDocument(new XElement(ns + "foo",
                                        settings));

        Console.Write(file.ToString());            
    }

这个操作的结果是...

<foo xmlns="http://tempuri.org/KeyEmFileSchema.xsd/">
  <settings>
    <colormaps>
      <colormap color="Gray" textcolor="Black" />
      <colormap color="DarkGray" textcolor="White" />
      <colormap color="Black" textcolor="White" />
      <colormap color="Cyan" textcolor="Black" />
    </colormaps>
    <macromaps>
      <macromap pattern="^@([0-9A-F]{2})\|([0-9A-F]{2})$" replace="{ESC}$1{ESC}$2{MOUSERESET}" />
      <macromap pattern="^\$([0-9A-F]{2})\|([0-9A-F]{2})$" replace="{USERCLICK}{ESC}$1{ESC}$2{MOUSERESET}" />
      <macromap pattern="^\$([0-9A-F]{2})$" replace="{USERCLICK}{ESC}$1" />
    </macromaps>
    <keydefault color="Cyan" />
    <groupdefault color="DarkGray" />
  </settings>
</foo>

正如您所看到的,settings元素现在与foo元素在同一个命名空间中。这实质上是一个快速而不太规范的XML转换,显然它不会遵守您导入的XML文档中的任何命名空间。但这可能是您想要的,或者至少可以作为更强大的东西的基础。


你需要使用Xslt技术转换文档,或者在代码中读取每个元素并进行转换。基本上,你加载的XDocument知道该文档中每个元素的命名空间,并且知道它与foo的命名空间不同。 - Martin Peck
我可以更改我读取的 XML 文件以使其处于正确的命名空间中吗? - magol
你有你的设置 XML 的片段/示例吗? - Martin Peck
另外,你的代码示例无法编译。你删除了其中的某些部分吗?第二行看起来不对。 - Martin Peck
@magol,我猜想您并不关心XML文件的命名空间,您只是希望这些元素与输出文档中的命名空间相同,以内联方式出现,对吗? - Martin Peck
显示剩余2条评论

2

您可以编写一个扩展方法来实现此功能。该方法具有返回值,因此支持链接,但也会更改原始转换,因此可以在不进行赋值的情况下使用。

public static XElement EnsureNamespaceExists(this XElement xElement, XNamespace xNamespace)
{
    string nodeName = xElement.Name.LocalName;

    if (!xElement.HasAttribute("xmlns"))
    {
        foreach (XElement tmpElement in xElement.DescendantsAndSelf())
        {
            tmpElement.Name = xNamespace + tmpElement.Name.LocalName;
        }
        xElement = new XElement(xNamespace + nodeName, xElement.FirstNode);
    }

    return xElement;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接