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

  • 本文关键字:父节点 文件 DGML xmlns c# dgml
  • 更新时间 :
  • 英文 :


当我保存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>

如您所见,XNameSpace xmlns=""出现在父节点、NodesLinksCategories之后。如何删除它?

这是因为

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

这就是为什么在输出 XML 时,这些元素具有 xmlns 属性来区分它们不在同一命名空间中。

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

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

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

或者,请参阅此处了解对文档中的所有子节点执行此操作的方法。

最新更新