1

When I save a DGML file, unnecessary XNamespace appears.

This is a code of saving DGML file.

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);
}

And this is an output DGML file.

<?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>

As you can see, xmlns="" of XNameSpace appears after the parents' node, Nodes, Links, and Categories. How can I remove it?

Alex
  • 2,931
  • 6
  • 15
  • 35
Masahiro
  • 125
  • 8

1 Answers1

2

It's because when you set the namespace on the root element to http://schemas.microsoft.com/vs/2009/dgml, it's only affecting that element, it doesn't become the default for the whole document - child elements you add to it will still have a default/empty namespace.

That's why, when the XML is output those elements have the xmlns attribute to distinguish that they are not in the same namespace.

To change that, when creating the child elements you can add the namespace as you have done for the DirectedGraph root element - for example:

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

Once they have the same element as the root node, they will no longer be output with an empty xmlns attribute.

Alternatively, see here for a method to do that for all child nodes in a document.

steve16351
  • 4,777
  • 2
  • 12
  • 27