【问题标题】:C# remove attribute from root nodeC#从根节点删除属性
【发布时间】:2013-10-22 23:35:56
【问题描述】:

我尝试解析一个 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");

我该怎么办?

【问题讨论】:

  • 格式良好的 XML 应该具有 xmlns 属性。
  • 删除命名空间是实际要求吗?您的要求不只是能够解析xml文件吗?如果我是对的,你必须处理 Xml 命名空间。

标签: c# 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);

【讨论】:

    【解决方案2】:

    用途:

    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

    【讨论】:

      猜你喜欢
      • 2017-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多