简体   繁体   English

如何在c#中忽略XML文档中的命名空间?

[英]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. 我正在尝试在c#中打开一个XML文件,按属性名称查找节点,该节点工作正常,然后在同一节点中显示XML属性的名称。

My code is simple (as I pinched it from other sources!) and works on my test XML doc. 我的代码很简单(因为我从其他来源捏了它!)并且在我的测试XML文档上工作。 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. 我一直在拉我的头发(不是我剩下的很多)并且发现它是因为我正在使用的实际文件中的xmlns属性。 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. 当xmlns未包含在文件中时,上述代码可以正常工作。 However, when xmlns is included the orient variable is null. 但是,当包含xmlns时,orient变量为null。 The xmlns path doesn't exist, when i try to navigate to it in a browser I get a 404 error. xmlns路径不存在,当我尝试在浏览器中导航到它时,我收到404错误。

Not sure what a xml namespace is to be honest, but I have thousands of these files and can't manually edit them. 不确定xml命名空间是诚实的,但我有数千个这样的文件,无法手动编辑它们。 Is there an easy way to get C# to overlook the namespace and just pretend it's not there? 是否有一种简单的方法可以让C#忽略命名空间并假装它不在那里? I've tried with Xpath, but that just blew my mind! 我试过Xpath,但这让我大吃一惊!

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. 无论如何,我必须使用xmlnamespacenmanager来声明与xml文件中相同的命名空间。 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?! 现在我的下一个挑战是尝试从xml文件中读取bmp,应该很简单,对吧?!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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