Victor Zhang
Victor Zhang

Reputation: 52

How to Select XML Nodes with XML Namespaces with C#

I have to analyze a XML doc with special namespace using C#, and I get some idea from this post. But my code fail to get the expected XML node, because the XML structure is very special...

There is a namespace in root node in XML

<MDOC xmlns="urn:schemas-microsoft-com/PSS/PSS_Survey01">

Here is my code to get this root node

        XmlDocument doc = new XmlDocument();
        doc.Load(path);

        XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
        nsmgr.AddNamespace("urn", "schemas-microsoft-com/PSS/PSS_Survey01");

        XmlNode root = doc.SelectSingleNode("MDOC", nsmgr);

Help me!

Upvotes: 0

Views: 2199

Answers (1)

Milind Thakkar
Milind Thakkar

Reputation: 980

I am not sure what is special about your XML structure.

I would write the code little differently

string xmlNamespace = String.Empty;
XmlNamespaceManager nsmgr;
XmlNodeList nodeInfo = FABRequestXML.GetElementsByTagName("RootNodeName");
xmlNamespace = Convert.ToString(nodeInfo[0].Attributes["xmlns"].Value);
nsmgr = new XmlNamespaceManager(MyXml.NameTable);
nsmgr.AddNamespace("AB", xmlNamespace);

XmlNode myNode = MyXml.DocumentElement.SelectSingleNode("AB:NodeName", nsmgr);

Hope that helps

Upvotes: 3

Related Questions