1

I tries to parse a XML file (get it from Dependacy Graph in VS 2012).

Here is sample of my .xml file

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

in here, I needs to remove attribute "xmlns" from DirectedGraph.

here's my source to remove this

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

but this code doesn't work. If I don't delete this I can't select node like

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

What should I do?

ARN
  • 13
  • 1
  • 5
  • A well formed XML should have the xmlns attribute. – Matthias Oct 15 '13 at 08:46
  • Is removing the namespace the actual requirement? Isn't your requirement simply to be able to parse the xml file? If I'm right, you have to deal with Xml namespaces. – Steve B Oct 15 '13 at 08:47

2 Answers2

1

Use:

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

Taken from: How to remove all namespaces from XML with C#?.

You might also want to check out: XmlSerializer: remove unnecessary xsi and xsd namespaces.

Community
  • 1
  • 1
Igor Ševo
  • 5,459
  • 3
  • 35
  • 80
1

If you like you can work with the namespace instead of removing the declaration:

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);
Gene
  • 4,192
  • 5
  • 32
  • 56