Quinn Wilson
Quinn Wilson

Reputation: 8261

Adding a NameSpace to an XmlDocument by CreateAttribute("xmlns") doesn't work

Is this a bug or am I doing something wrong? I create an XmlDocument in code, I add a namespace to it with XmlNamespaceManager and then try to query the document. It fails to find the element, however if I doc.LoadXml(doc.OuterXml) it goes on to find the element.

So doc.LoadXml(doc.OuterXml) is a hack that doesn't make sense to me:

a) why doesn't my code work without it?
b) why does it work with it?

        var ns = "http://made.up/uri";
        var doc = new XmlDocument();
        doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", null));

        var policies = doc.AppendChild(doc.CreateElement("policies"));
        var att = policies.Attributes.Append(doc.CreateAttribute("xmlns"));

        att.Value = ns;
        var policy = policies.AppendChild(doc.CreateElement("policy"));
        policy.InnerText="bla";

        // doc.LoadXml(doc.OuterXml); // if I uncomment this the SelectNodes() below works

        var namespaces = new XmlNamespaceManager(doc.NameTable);
        namespaces.AddNamespace("pol", ns);

        var policyNodes = doc.SelectNodes("//pol:policy", namespaces);

        if (policyNodes.Count == 0){
            Console.WriteLine("No policy nodes");
        }else{
            Console.WriteLine("Found policy nodes");
        }
        Console.WriteLine(doc.OuterXml + "\n" + DateTime.Now);

Dotnet fiddle here : https://dotnetfiddle.net/DQGwH2

Upvotes: 1

Views: 1731

Answers (1)

Quinn Wilson
Quinn Wilson

Reputation: 8261

Found my own answer.

If you want to add a namespace to an XmlDocument, you do it by adding it as an argument to your CreateElement()

If you just create an attribute with xmlns="namespace" it doesn't scope anything as in that namespace (it's just an attribute.)

as in: var policies = doc.AppendChild(doc.CreateElement("policies","http://namespace.uri"));

That's why doc.LoadXml(doc.OuterXml) works, it actually reads it as a namespace

updated fiddle https://dotnetfiddle.net/sNdH6R

Upvotes: 2

Related Questions