Parse XDocument without having to keep specifying the default namespace

前端 未结 5 1695
北荒
北荒 2021-02-13 16:51

I have some XML data (similar to the sample below) and I want to read the values in code.

Why am I forced to specify the default namespace to access each element? I woul

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-13 17:30

    As suggested by this answer, you can do this by removing all namespaces from the in-memory copy of the document. I suppose this should only be done if you know you won't have name collisions in the resulting document.

    /// 
    /// Makes parsing easier by removing the need to specify namespaces for every element.
    /// 
    private static void RemoveNamespaces(XDocument document)
    {
        var elements = document.Descendants();
        elements.Attributes().Where(a => a.IsNamespaceDeclaration).Remove();
        foreach (var element in elements)
        {
            element.Name = element.Name.LocalName;
    
            var strippedAttributes =
                from originalAttribute in element.Attributes().ToArray()
                select (object)new XAttribute(originalAttribute.Name.LocalName, originalAttribute.Value);
    
            //Note that this also strips the attributes' line number information
            element.ReplaceAttributes(strippedAttributes.ToArray());
        }
    }
    

提交回复
热议问题