2013-10-15 102 views
1

我試圖解析一個XML文件(從VS 2012中的Dependacy Graph中獲取它)。C#從根節點刪除屬性

這裏是我的.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"); 

我該怎麼辦?

+0

一個良好的XML應該有xmlns屬性。 – Matthias

+0

是否刪除名稱空間的實際要求?不是你的要求只是爲了能夠解析XML文件?如果我是對的,你必須處理Xml命名空間。 –

回答

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); 
+0

謝謝!它完美的作品。 – ARN

1

用途:How to remove all namespaces from XML with C#?

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

取之。

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