为啥xmlns出现在DGML文件写入的父节点?
Posted
技术标签:
【中文标题】为啥xmlns出现在DGML文件写入的父节点?【英文标题】:Why xmlns appears at the parents' node in DGML file writing?为什么xmlns出现在DGML文件写入的父节点? 【发布时间】:2019-07-26 13:15:09 【问题描述】:当我保存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=""
出现在父节点Nodes
、Links
和Categories
之后。
如何删除它?
【问题讨论】:
【参考方案1】:这是因为当您将根元素上的命名空间设置为 http://schemas.microsoft.com/vs/2009/dgml
时,它只会影响 那个 元素,它不会成为整个文档的默认值 - 您添加到它的子元素仍然会有一个默认/空的命名空间。
这就是为什么在输出 XML 时,这些元素具有xmlns
属性来区分它们不在同一个命名空间中。
要改变这一点,在创建子元素时,您可以像为 DirectedGraph
根元素所做的那样添加命名空间 - 例如:
XElement nodes = new XElement(xNamespace + "Nodes");
一旦它们具有与根节点相同的元素,它们将不再以空的xmlns
属性输出。
或者,see here 用于为文档中的所有子节点执行此操作的方法。
【讨论】:
以上是关于为啥xmlns出现在DGML文件写入的父节点?的主要内容,如果未能解决你的问题,请参考以下文章
为啥我的网站没有加载,而是出现此错误 - “Smarty:无法写入文件”?