locked
How to extract the namespace from xml and declare one if none RRS feed

  • Question

  • Hi,

    I have the following xml :

    <?xml version="1.0" encoding="utf-8" standalone="no"?>
    <container xmlns="urn:oasis:names:tc:opendocument:xmlns:container" version="1.0">
    	<rootfiles>
    		<rootfile full-path="EPUB/package.opf" media-type="application/oebps-package+xml"/>
    	</rootfiles>
    </container>
    

    and basically I need to extract < rootfile > information, so I did this :

    private static string xmlText = 
                "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"no\"?>" +
                "<container xmlns=\"urn:oasis:names:tc:opendocument:xmlns:container\" version=\"1.0\">" +
                	"<rootfiles>" +
                		"<rootfile full-path=\"EPUB/package.opf\" media-type=\"application/oebps-package+xml\"/>" +
                	"</rootfiles>" +
                "</container>";
    
            private void TestXml()
            {
                XmlLoadSettings xmlSettings = new XmlLoadSettings();
                xmlSettings.ElementContentWhiteSpace = false;
                xmlSettings.MaxElementDepth = 100;
                xmlSettings.ResolveExternals = true;
                xmlSettings.ValidateOnParse = false;
    
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.LoadXml(xmlText, xmlSettings);
                var nsUri = xmlDoc.NamespaceUri;
                var pkgNodes = xmlDoc.SelectNodesNS("/ocf:container/ocf:rootfiles/ocf:rootfile", "xmlns:ocf=\"urn:oasis:names:tc:opendocument:xmlns:container\"");
                foreach(var pkgNode in pkgNodes)
                {
                    IXmlNode xmlNode;
    		        xmlNode = pkgNode.Attributes.GetNamedItem("full-path");
    		        String full_path = (xmlNode != null)? xmlNode.InnerText : null;
                }
                
            }

    However the namespace might not be present, so how can I get the xmlns if available and declare one by default if it's not

    to be able to handle both case with the same code ?

    Thanks

    Monday, February 3, 2014 4:25 PM

All replies