C#从根节点删除属性

时间:2013-10-15 08:33:07

标签: c# xml

我尝试解析XML文件(从VS 2012中的Dependacy Graph获取)。

以下是我的.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");

我该怎么办?

2 个答案:

答案 0 :(得分: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)));
}

取自:How to remove all namespaces from XML with C#?

您可能还想查看:XmlSerializer: remove unnecessary xsi and xsd namespaces

答案 1 :(得分: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);