简体   繁体   中英

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM