为什么xmlns出现在DGML文件写入的父节点?

Why xmlns appears at the parents' node in DGML file writing?

当我保存一个 DGML 文件时,出现不必要的 XNamespace

这是保存DGML文件的代码。

public void saveDGMLFile()
{
    Debug.Log("Save DGML file!");

    XNamespace xNamespace = "http://schemas.microsoft.com/vs/2009/dgml";
    xDoc = new XDocument();
    XElement root = new XElement(
        xNamespace + "DirectedGraph",
        new XAttribute("name", "root"));

    xDoc.Add(root);
    XElement parent = xDoc.Root;
    XElement nodes = new XElement("Nodes");

    foreach (var e in exploded_positions)
    {

        XElement item = new XElement("Node");
        item.SetAttributeValue("Id", e.Item1.name);
        item.SetAttributeValue("Category", 0);
        item.SetAttributeValue(XmlConvert.EncodeName("start_position"), (e.Item2.x + " " + e.Item2.y + " " + e.Item2.z));
        item.SetAttributeValue(XmlConvert.EncodeName("end_position"), (e.Item3.x + " " + e.Item3.y + " " + e.Item3.z));
        nodes.Add(item);
    }

    parent.Add(nodes);

    XElement links = new XElement("Links");
    XElement link = new XElement("Link");
    links.Add(link);
    parent.Add(links);

    XElement categories = new XElement("Categories");
    XElement category = new XElement("category");
    categories.Add(category);
    parent.Add(categories);

    xDoc.Save(outputFileName);
}

这是一个输出 DGML 文件。

<?xml version="1.0" encoding="utf-8"?>
<DirectedGraph name="root" xmlns="http://schemas.microsoft.com/vs/2009/dgml">
  <Nodes xmlns="">
    <Node Id="PTC_EXP_Blasensensor-Adapter-+-" Category="0" start_position="0 0 0" end_position="0 0 -0.7573751" />
    <Node Id="PTC_EXP_BML_Mutter_UNF-2B_1-14-" Category="0" start_position="0 0 0" end_position="0 0.7573751 0" />
    <Node Id="PTC_EXP_BUSAKSHAMBAN_OR1501300N" Category="0" start_position="0 0 0" end_position="0.7573751 0 0" />
  </Nodes>
  <Links xmlns="">
    <Link />
  </Links>
  <Categories xmlns="">
    <category />
  </Categories>
</DirectedGraph>

如您所见,XNameSpacexmlns=""出现在父节点NodesLinksCategories之后。 我怎样才能删除它?

这是因为当您将根元素上的命名空间设置为 http://schemas.microsoft.com/vs/2009/dgml 时,它只会影响 那个 元素,它不会成为整个文档的默认值- 添加到其中的子元素仍将具有 default/empty 命名空间。

因此,当输出 XML 时,这些元素具有 xmlns 属性以区分它们不在同一命名空间中。

要改变这一点,在创建子元素时,您可以像为 DirectedGraph 根元素所做的那样添加命名空间 - 例如:

XElement nodes = new XElement(xNamespace + "Nodes");

一旦它们与根节点具有相同的元素,它们将不再以空 xmlns 属性输出。

或者,see here 为文档中的所有子节点执行此操作的方法。