简体   繁体   中英

How can I ignore the namespace in an XML document in c#?

I'm trying to open a XML file in c#, find a node by attribute name, which is working fine and then displaying the name of an XML attribute in the same node.

My code is simple (as I pinched it from other sources!) and works on my test XML doc. However, when I try it with an actual file it doesn't work. I've been pulling my hair out (not that I have much left) and have discovered it's because of the xmlns attribute in the actual files I'm using. The path to the namespace does not exist.

My code is as follows:

XmlDocument doc = new XmlDocument();
doc.Load(@"c:\deroschedule\test.sym");
var orient = doc.SelectSingleNode("//Attr[@name='Orientation]/@value");

the above code works perfectly when xmlns is not included in the file. However, when xmlns is included the orient variable is null. The xmlns path doesn't exist, when i try to navigate to it in a browser I get a 404 error.

Not sure what a xml namespace is to be honest, but I have thousands of these files and can't manually edit them. Is there an easy way to get C# to overlook the namespace and just pretend it's not there? I've tried with Xpath, but that just blew my mind!

Ok I figured it out for myself. Thought I would post the answer here even though there are thousands of other answers apparently.

Where I went wrong was misunderstanding what the namespace actually does. Anyway I had to use xmlnamespacenmanager to declare the same namespace as in the xml file. Then I had to use the namespace in the query.

XmlDocument doc = new XmlDocument();
doc.Load(@"C:\deroschedule\test6.sym");
XmlNamespaceManager ns = new XmlNamespaceManager(doc.NameTable);
ns.AddNamespace("ma", "http://www.yournamespaceinfohere.com/");
var orient = doc.SelectSingleNode("//ma:attr[@name='Orientation']/@value", ns);

Now my next challenge is to try and read the bmp from the xml file, should be easy, right?!

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