tags:

views:

1001

answers:

3

I have several xml files whose postfix is not .xml, but .component Now I want to handle them in the c# program, but It seems that the c# cant even find the root element of these xml files

var doc = new XmlDocument();
doc.Load(path); // MG: edited to Load based on comment
XmlNode root = doc.SelectSingleNode("rootNodename");

It seems that the root is null, How should I cope with this?

+4  A: 

LoadXml takes an XML string, not a file path. Try Load instead. Load doesn't care about the file extension.

Here is a link to the documention for Load: http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.load.aspx

Dave76
Yes I made a mistake when I wrote the questionActually I tried Load() too, LoadXml will generate a exception while Load() will load the file without problem but I just can not find the root node, the return is always null
abusemind
Actually, I expect the real problem is namespaces... (see answer)
Marc Gravell
A: 

Check How to deal with XML in C#

Freddy
+2  A: 

Given that you've resolved the Load/LoadXml confusion, I expect the issue is namespaces; do you have example xml? Handling xml with namespaces gets... "fun" ;-p

For example:

    XmlDocument doc = new XmlDocument();
    doc.LoadXml(@"<test xmlns='myFunkyUri' value='abc'/>");
    // wrong; no namespace consideration
    XmlElement root = (XmlElement)doc.SelectSingleNode("test");
    Console.WriteLine(root == null ? "(no root)" : root.GetAttribute("value"));
    // right
    XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
    nsmgr.AddNamespace("x", "myFunkyUri"); // x is my alias for myFunkyUri
    root = (XmlElement)doc.SelectSingleNode("x:test", nsmgr);
    Console.WriteLine(root == null ? "(no root)" : root.GetAttribute("value"));

Note that even if your xml declares xml aliases, you may still need to re-declare them for your namespace-manager.

Marc Gravell
Yes, There actually some interesting problems with the default namespace(the one without prefix)
abusemind