1

我尝试解析一个 XML 文件(从 VS 2012 中的依赖关系图中获取)。

这是我的 .xml 文件的示例

<?xml version="1.0" encoding="utf-8"?>
<DirectedGraph xmlns="http://schemas.microsoft.com/vs/2009/dgml">
    <Nodes>
        <Node Id="@101" Category="CodeSchema_ProjectItem" FilePath="$(ProgramFiles)\windows kits\8.0\include\um\unknwnbase.h" Label="unknwnbase.h" />
        <Node Id="@103" Category="CodeSchema_ProjectItem" FilePath="$(ProgramFiles)\windows kits\8.0\include\shared\wtypesbase.h" Label="wtypesbase.h" />

在这里,我需要从 DirectedGraph 中删除属性“xmlns”。

这是我删除它的来源

XmlNodeList rootNode = xmlDoc.GetElementsByTagName("DirectedGraph");
foreach (XmlNode node in rootNode)
{
    node.Attributes.RemoveNamedItem("xmlns");
}

但这段代码不起作用。如果我不删除这个我不能选择像这样的节点

XmlNodeList nodes = xmlDoc.DocumentElement.SelectNodes("/DirectedGraph/Nodes/Node");

我该怎么办?

4

2 回答 2

1

采用:

private static XElement RemoveAllNamespaces(XElement xmlDocument)
{
    if (!xmlDocument.HasElements)
    {
        XElement xElement = new XElement(xmlDocument.Name.LocalName);
        xElement.Value = xmlDocument.Value;
        foreach (XAttribute attribute in xmlDocument.Attributes())
            xElement.Add(attribute);
            return xElement;
     }
     return new XElement(xmlDocument.Name.LocalName, xmlDocument.Elements().Select(el => RemoveAllNamespaces(el)));
}

摘自:如何使用 C# 从 XML 中删除所有命名空间?.

您可能还想查看:XmlSerializer:删除不必要的 xsi 和 xsd 命名空间

于 2013-10-15T08:46:16.490 回答
1

如果您愿意,可以使用命名空间而不是删除声明:

var xml = @"<?xml version=""1.0"" encoding=""utf-8""?>
<DirectedGraph xmlns=""http://schemas.microsoft.com/vs/2009/dgml"">
  <Nodes>
      <Node Id=""@101"" Category=""CodeSchema_ProjectItem"" FilePath=""$(ProgramFiles)\windows kits\8.0\include\um\unknwnbase.h"" Label=""unknwnbase.h"" />
      <Node Id=""@103"" Category=""CodeSchema_ProjectItem"" FilePath=""$(ProgramFiles)\windows kits\8.0\include\shared\wtypesbase.h"" Label=""wtypesbase.h"" />
  </Nodes>
</DirectedGraph>";

var doc = new XmlDocument();
doc.LoadXml(xml);

var manager = new XmlNamespaceManager(doc.NameTable);
manager.AddNamespace("d", "http://schemas.microsoft.com/vs/2009/dgml");

var nodes = doc.DocumentElement.SelectNodes("/d:DirectedGraph/d:Nodes/d:Node", manager);
Console.WriteLine(nodes.Count);
于 2013-10-15T08:47:02.873 回答